Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - onclick="" vs event handler

If I want a function to be executed, I prefer doing inline js:

<p id="element" onclick="doSomething();">Click me</p>

because it is easier to debug.

However, I hear people saying not to use inline js, and do:

document.getElementById('element').onclick = doSomething;

Why is the js event listener recommended?

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

One big argument against inline event handlers, and the argument that is addressed by the other answers here is the separation of presentation and logic.

However, there is actually a bigger problem IMO: The somehow elusive way how inline event handlers are evaluated.

As you may know, the content of the on* attributes will be used as body of the event handler function. But what characteristics does this function have?

One of the surprising ones is that properties of some ancestor elements and of the element itself are in the scope of the inline event handler.

<form>
    <input name="foo" />
    <button type="button" onclick="console.log(foo); console.log(window.foo);">
        Click me
    </button>
    <div onclick="console.log(foo);">Click me as well!</div>
</form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...