我有一个巨大的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.
<whatever onclick="doStuff();" onmouseover="in()" onmouseout="out()" />
onclick, onmouseover, onmouseout等事件实际上对性能不好(主要是在ie中,去想想)。如果您使用Visual Studio进行编码,当您使用这些代码运行一个页面时,其中的每一个都将创建一个单独的SCRIPT块,占用内存,从而降低性能。
更不用说你应该有一个分离的关注点:JavaScript和布局应该分开!
为这些事件创建evenHandlers总是更好的,一个事件可以捕获数百/数千个项目,而不是为每个事件创建数千个单独的脚本块!
(还有,所有人都在说的话。)