我有一个巨大的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
}
在我的应用程序中,我使用第一种或第二种方法。哪个更好?性能更好?和标准?
恕我直言,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.
为了获得更好的性能,请使用本机JavaScript。为了更快地开发,请使用jQuery。查看jQuery和原生元素性能的比较。
我在Windows Server 2008 R2 / 7 64位的Firefox 16.0 32位上进行了测试
$('span'); // 6,604 operations per second
document.getElementsByTagName('span'); // 10,331,708 operations/sec
对于点击事件,检查本机浏览器事件vs jquery触发器或jquery vs本机点击事件绑定。
在Windows Server 2008 R2 / 7 64位的Chrome 22.0.1229.79 32位上测试
$('#jquery a').click(window.testClickListener); // 2,957 operations/second
[].forEach.call( document.querySelectorAll('#native a'), function(el) {
el.addEventListener('click', window.testClickListener, false);
}); // 18,196 operations/second