我有一个巨大的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更好,因为它将JavaScript代码从HTML中分离出来。必须尽量保持页面行为和结构的不同。这很有帮助。

其他回答

大多数情况下,当性能是唯一的标准时,原生JavaScript方法是比jQuery更好的选择,但是jQuery利用了JavaScript并使开发变得容易。可以使用jQuery,因为它不会严重降低性能。在你的具体情况下,性能的差异是可以忽略的。

你可以结合它们,使用jQuery将函数绑定到点击

<div id="myDiv">Some Content</div>

$('#myDiv').click(divFunction);

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

$ (" # myDiv”)。click更好,因为它将JavaScript代码从HTML中分离出来。必须尽量保持页面行为和结构的不同。这很有帮助。