Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

eventhandler - How does the way in which a JavaScript event handler is assigned affect its execution?

Please, consider the following code.

<!DOCTYPE html>
<title>Question</title>
<script>
    function report(handler, _this) {
        alert(
            "handler:
" + handler + "
" +
            "this: " + _this + "
" +
            "event: " + event + "
"
        )
    }
</script>
<input type=button id=A value=A onclick="report(A.onclick, this)">
<script>function f() {report(B.onclick, this)}</script>
<input type=button id=B value=B onclick="f()">
<input type=button id=C value=C>
<script>C.onclick = function () {report(C.onclick, this)}</script>

By clicking the buttons, I have seen that:

  1. A.onclick and B.onclick are wrapped in "function onclick(event) {...}".
  2. In B.onclick, this is the window (rather than a button).

Are there any other considerations?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is another consideration. Consider the following code.

<!DOCTYPE html>
<title>Answer</title>
<script type=module>function f() {alert(1)}</script>
<input type=button value=1 onclick=f()>
<input type=button value=2 id=button>
<script type=module>button.onclick = function () {alert(2)}</script>

f is undefined in onclick for the button with value=1 (because f is defined in a module). So, when an event handler must execute code in a module (e.g., code that uses import), the event handler must be assigned in the module.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...