我有一个巨大的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背后的主要思想之一是将JavaScript与令人讨厌的HTML代码分开。第一种方法是要走的路。

其他回答

恕我直言,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.

使用$('#myDiv').click(function(){更好,因为它遵循标准的事件注册模型。(jQuery内部使用addEventListener和attachEvent)。

基本上,以现代方式注册事件是处理事件的一种不引人注目的方式。另外,要为目标注册多个事件监听器,可以为同一个目标调用addEventListener()。

var myEl = document.getElementById('myelement');

myEl.addEventListener('click', function() {
    alert('Hello world');
}, false);

myEl.addEventListener('click', function() {
    alert('Hello world again!!!');
}, false);

http://jsfiddle.net/aj55x/1/

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属性,示例:

<button onclick="alert('Hello world!')">

或DOM元素属性,示例:

myEl.onclick = function(event){alert('Hello world');}; 

都是旧的,而且很容易被重写。

应该避免使用HTML属性,因为它会使标记更大,可读性更差。内容/结构和行为的关注点没有很好地分开,使得错误更难被发现。

DOM元素属性方法的问题在于,每个事件只能将一个事件处理程序绑定到一个元素。

更多关于传统事件处理-> http://www.quirksmode.org/js/events_tradmod.html

MDN参考:https://developer.mozilla.org/en-US/docs/DOM/event

Onclick函数Jquery

$(" #选择器”).click(函数(){ / /你的功能 });

<whatever onclick="doStuff();" onmouseover="in()" onmouseout="out()" />

onclick, onmouseover, onmouseout等事件实际上对性能不好(主要是在ie中,去想想)。如果您使用Visual Studio进行编码,当您使用这些代码运行一个页面时,其中的每一个都将创建一个单独的SCRIPT块,占用内存,从而降低性能。

更不用说你应该有一个分离的关注点:JavaScript和布局应该分开!

为这些事件创建evenHandlers总是更好的,一个事件可以捕获数百/数千个项目,而不是为每个事件创建数千个单独的脚本块!

(还有,所有人都在说的话。)

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