我有一个巨大的 jQuery 应用程序,我使用以下两种方法来处理单击事件。
第一种方法
HTML
<div id="myDiv">Some Content</div>
jQuery
$('#myDiv').click(function(){
//Some code
});
第二种方法
HTML
<div id="myDiv" onClick="divFunction()">Some Content</div>
JavaScript 函数调用
function divFunction(){
//Some code
}
我在我的应用程序中使用第一种或第二种方法。哪一个更好?性能更好?标准吗?
最佳答案
使用 $('#myDiv').click(function(){
更好,因为它遵循标准事件注册模型。(jQuery internally 使用 addEventListener
和 attachEvent
) .
基本上,在 modern way 中注册事件就是 unobtrusive 处理事件的方式。另外,要为目标注册多个事件监听器,您可以为同一目标调用 addEventListener()
。
var myEl = document.getElementById('myelement');
myEl.addEventListener('click', function() {
alert('Hello world');
}, false);
myEl.addEventListener('click', function() {
alert('Hello world again!!!');
}, false);
Why use addEventListener? (From MDN)
addEventListener is the way to register an event listener as specified in W3C DOM. Its benefits are as follows:
- It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla extensions that need to work well even if other libraries/extensions are used.
- It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)
- It works on any DOM element, not just HTML elements.
有关现代事件注册的更多信息 -> http://www.quirksmode.org/js/events_advanced.html
其他方法如设置 HTML attributes ,示例:
<button onclick="alert('Hello world!')">
或者 DOM element properties ,例如:
myEl.onclick = function(event){alert('Hello world');};
很旧,很容易被覆盖。
应避免HTML 属性,因为它会使标记更大且可读性较差。对内容/结构和行为的关注点没有很好地分开,使得错误更难被发现。
DOM 元素属性方法的问题是每个事件只能将一个事件处理程序绑定(bind)到一个元素。
有关传统事件处理的更多信息 -> http://www.quirksmode.org/js/events_tradmod.html
关于javascript - jQuery.click() 与 onClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30691462/