我有一个巨大的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
}
在我的应用程序中,我使用第一种或第二种方法。哪个更好?性能更好?和标准?
在我看来,你的问题并不是关于是否使用jQuery。而是:在HTML中内联绑定事件更好,还是通过事件监听器绑定事件更好?
不支持内联绑定。此外,通过这种方式,您只能将一个函数绑定到某个事件。
因此,我建议使用事件侦听器。通过这种方式,您将能够将许多函数绑定到单个事件,并在需要时稍后取消它们的绑定。考虑这段纯JavaScript代码:
querySelector('#myDiv').addEventListener('click', function () {
// Some code...
});
这在大多数现代浏览器中都有效。
然而,如果你已经在你的项目中包含了jQuery -只需使用jQuery: .on或.click函数。
恕我直言,onclick是优于.click的首选方法,仅当满足以下条件时:
页面上有很多元素
要为单击事件注册的事件只有一个
你担心手机性能/电池寿命
I formed this opinion because of the fact that the JavaScript engines on mobile devices are 4 to 7 times slower than their desktop counterparts which were made in the same generation. I hate it when I visit a site on my mobile device and receive jittery scrolling because the jQuery is binding all of the events at the expense of my user experience and battery life. Another recent supporting factor, although this should only be a concern with government agencies ;) , we had IE7 pop-up with a message box stating that JavaScript process is taking to long...wait or cancel process. This happened every time there were a lot of elements to bind to via jQuery.
不同的作品。如果使用click(),则可以添加几个函数,但如果使用属性,则只执行一个函数—最后一个函数。
DEMO
HTML
<span id="JQueryClick">Click #JQuery</span> </br>
<span id="JQueryAttrClick">Click #Attr</span> </br>
JavaScript
$('#JQueryClick').click(function(){alert('1')})
$('#JQueryClick').click(function(){alert('2')})
$('#JQueryAttrClick').attr('onClick'," alert('1')" ) //This doesn't work
$('#JQueryAttrClick').attr('onClick'," alert('2')" )
如果我们谈论的是性能,在任何情况下直接使用总是更快,但使用属性,您将只能分配一个函数。