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
158 views
in Technique[技术] by (71.8m points)

javascript - Difference between "click" and onclick

What is the difference between click in

document.getElementById("myBtn").addEventListener("click", displayDate);    

and onclick in

<!DOCTYPE html>
<html>
<body>

<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>

</body>
</html> 

Are they both considered as events? Why can't we use click instead of onclick and visce versa?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The difference is that the first is an event listener, and the second is an event handler content attribute.

Event handler content attributes store an internal raw uncompiled handler, which produces an event listener via the event handler processing and getting the current value of the event handler algorithms.

In practice, this affects the scope, e.g.

(function() { var element = document.body;
  var str = "console.log([typeof foo, typeof bar])";
  var func = function() { console.log([typeof foo, typeof bar]); };
  element.foo = 'foo';
  var bar = 'bar';
  element.setAttribute('onclick', str);
  element.addEventListener('click', func);
  element.click();
  // Event handler content attribute logs ["string", "undefined"]
  // Event listener logs ["undefined", "string"]
})();

I discourage using event handlers. They are an old reminiscence and are superseded by event listeners.


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

...