Javascript jQuery.click() 与 onClick
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12627443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery.click() vs onClick
提问by Techie
I have a huge jQuery application, and I'm using the below two methods for click events.
我有一个巨大的 jQuery 应用程序,我使用以下两种方法来处理点击事件。
First method
第一种方法
HTML
HTML
<div id="myDiv">Some Content</div>
jQuery
jQuery
$('#myDiv').click(function(){
//Some code
});
Second method
第二种方法
HTML
HTML
<div id="myDiv" onClick="divFunction()">Some Content</div>
JavaScript function call
JavaScript 函数调用
function divFunction(){
//Some code
}
I use either the first or second method in my application. Which one is better? Better for performance? And standard?
我在我的应用程序中使用第一种或第二种方法。哪一个更好?性能更好?和标准?
回答by Selvakumar Arumugam
Using $('#myDiv').click(function(){
is betteras it follows standard event registration model. (jQuery internallyuses addEventListener
and attachEvent
).
使用$('#myDiv').click(function(){
是更好的,因为它遵循标准的事件注册模型。(jQuery 在内部使用addEventListener
和attachEvent
)。
Basically registering an event in modern wayis the unobtrusiveway of handling events. Also to register more than one event listener for the target you can call addEventListener()
for the same target.
基本上以现代方式注册事件是处理事件的不显眼的方式。此外,要为目标注册多个事件侦听器,您可以addEventListener()
为同一目标调用。
var myEl = document.getElementById('myelement');
myEl.addEventListener('click', function() {
alert('Hello world');
}, false);
myEl.addEventListener('click', function() {
alert('Hello world again!!!');
}, false);
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.
为什么要使用 addEventListener?(来自 MDN)
addEventListener 是注册 W3C DOM 中指定的事件侦听器的方法。它的好处如下:
- 它允许为一个事件添加多个处理程序。这对于即使使用其他库/扩展也需要正常工作的 DHTML 库或 Mozilla 扩展特别有用。
- 当侦听器被激活(捕获与冒泡)时,它可以让您对相位进行更细粒度的控制
- 它适用于任何 DOM 元素,而不仅仅是 HTML 元素。
More about Modern event registration -> http://www.quirksmode.org/js/events_advanced.html
更多关于现代事件注册 -> http://www.quirksmode.org/js/events_advanced.html
Other methods such as setting the HTML attributes, example:
其他方法如设置HTML 属性,例如:
<button onclick="alert('Hello world!')">
Or DOM element properties, example:
或DOM 元素属性,例如:
myEl.onclick = function(event){alert('Hello world');};
are old and they can be over written easily.
是旧的,它们可以很容易地被覆盖。
HTML attributeshould be avoided as It makes the markup bigger and less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find.
应避免使用HTML 属性,因为它会使标记更大且可读性更低。对内容/结构和行为的关注没有很好地分开,使得错误更难找到。
The problem with the DOM element propertiesmethod is that only one event handler can be bound to an element per event.
DOM 元素属性方法的问题在于每个事件只能将一个事件处理程序绑定到一个元素。
More about Traditional event handling -> http://www.quirksmode.org/js/events_tradmod.html
更多关于传统事件处理 -> http://www.quirksmode.org/js/events_tradmod.html
MDN Reference: https://developer.mozilla.org/en-US/docs/DOM/event
回答by Marian Zburlea
For better performance, use the native JavaScript. For faster development, use jQuery. Check the comparison in performance at jQuery vs Native Element Performance.
为了获得更好的性能,请使用本机 JavaScript。为了更快的开发,请使用 jQuery。检查jQuery 与 Native Element Performance 的性能比较。
I've done a test in Firefox 16.0 32-bit on Windows Server 2008 R2 / 7 64-bit
我已经在 Windows Server 2008 R2 / 7 64 位上的 Firefox 16.0 32 位上做了一个测试
$('span'); // 6,604 operations per second
document.getElementsByTagName('span'); // 10,331,708 operations/sec
For click events, check Native Browser events vs jquery triggeror jQuery vs Native Click Event Binding.
对于单击事件,请检查Native Browser events vs jquery trigger或jQuery vs Native Click Event Binding。
Testing in Chrome 22.0.1229.79 32-bit on Windows Server 2008 R2 / 7 64-bit
在 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
回答by Micha? Miszczyszyn
From what I understand, your question is not really about whether to use jQuery or not. It's rather: Is it better to bind events inline in HTML or through event listeners?
据我了解,您的问题并不是关于是否使用 jQuery。而是:在 HTML 中内联绑定事件还是通过事件侦听器绑定事件更好?
Inline binding is deprecated. Moreover this way you can only bind one function to a certain event.
不推荐使用内联绑定。此外,通过这种方式,您只能将一个函数绑定到某个事件。
Therefore I recommend using event listeners. This way, you'll be able to bind many functions to a single event and to unbind them later if needed. Consider this pure JavaScript code:
因此我建议使用事件侦听器。这样,您就可以将多个函数绑定到单个事件,并在以后需要时解除绑定。考虑这个纯 JavaScript 代码:
querySelector('#myDiv').addEventListener('click', function () {
// Some code...
});
This works in most modern browsers.
这适用于大多数现代浏览器。
However, if you already include jQuery in your project — just use jQuery: .on
or .click
function.
但是,如果您已经在项目中包含了 jQuery — 只需使用 jQuery:.on
或.click
函数。
回答by CaffGeek
You could combine them, use jQuery to bind the function to the click
您可以组合它们,使用 jQuery 将函数绑定到点击
<div id="myDiv">Some Content</div>
$('#myDiv').click(divFunction);
function divFunction(){
//some code
}
回答by geekman
回答by Rahul
Go for this as it will give you both standard and performance.
去做这个,因为它会给你标准和性能。
$('#myDiv').click(function(){
//Some code
});
As the second method is simple JavaScript code and is faster than jQuery. But here performance will be approximately the same.
由于第二种方法是简单的 JavaScript 代码并且比 jQuery 更快。但这里的性能将大致相同。
回答by Thomas Vanderhoof
IMHO, onclick is the preferred method over .click only when the following conditions are met:
恕我直言,只有在满足以下条件时, onclick 是 .click 的首选方法:
- there are many elements on the page
- only one event to be registered for the click event
- You're worried about mobile performance/battery life
- 页面上有很多元素
- 只需为点击事件注册一个事件
- 您担心移动性能/电池寿命
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 引擎比同代的桌面引擎慢 4 到 7 倍。当我在移动设备上访问网站并收到抖动的滚动时,我讨厌它,因为 jQuery 以牺牲我的用户体验和电池寿命为代价绑定所有事件。另一个最近的支持因素,虽然这应该只与政府机构有关;),我们有 IE7 弹出消息框指出 JavaScript 进程需要很长时间...等待或取消进程。每次有很多元素要通过 jQuery 绑定时都会发生这种情况。
回答by Anton Baksheiev
Difference in works. If you use click(), you can add several functions, but if you use an attribute, only one function will be executed - the last one.
作品的差异。如果使用 click(),则可以添加多个函数,但如果使用属性,则只会执行一个函数——最后一个。
HTML
HTML
<span id="JQueryClick">Click #JQuery</span> </br>
<span id="JQueryAttrClick">Click #Attr</span> </br>
JavaScript
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')" )
If we are talking about performance, in any case directly using is always faster, but using of an attribute, you will be able to assign only one function.
如果我们谈论性能,无论如何直接使用总是更快,但是使用一个属性,您将只能分配一个功能。
回答by Chris
Seperation of concerns is key here, and so the event binding is the generally accepted method. This is basically what a lot of the existing answers have said.
关注点分离是这里的关键,因此事件绑定是普遍接受的方法。这基本上就是许多现有答案所说的。
Howeverdon't throw away the idea of declarative markup too quickly. It has it's place, and with frameworks like Angularjs, is the centerpiece.
但是,不要太快放弃声明性标记的想法。它占有一席之地,并且与 Angularjs 之类的框架一起,是核心。
There needs to be an understanding that the whole <div id="myDiv" onClick="divFunction()">Some Content</div>
was shamed so heavily because it was abused by some developers. So it reached the point of sacrilegious proportions, much like tables
. Some developers actuallyavoid tables
for tabular data. It's the perfect example of people acting without understanding.
需要有一个理解,整体<div id="myDiv" onClick="divFunction()">Some Content</div>
被羞辱得如此严重,因为它被一些开发者滥用了。所以它达到了亵渎神灵的地步,就像tables
. 一些开发人员实际上避免tables
使用表格数据。这是人们在没有理解的情况下行动的完美例子。
Although I like the idea of keeping my behaviour seperate from my views. I see no issue with the markup declaring whatit does (not howit does it, that's behaviour). It might be in the form of an actual onClick attribute, or a custom attribute, much like bootstraps javascript components.
虽然我喜欢让我的行为与我的观点分开的想法。我认为声明它做什么的标记没有问题(不是它是如何做的,那是行为)。它可能采用实际的 onClick 属性或自定义属性的形式,很像 bootstrap javascript 组件。
This way, by glancing just at the markup, you can see what is does, instead of trying to reverse lookup javascript event binders.
这样,只需看一眼标记,您就可以看到它的作用,而不是尝试反向查找 javascript 事件绑定器。
So, as a third alternative to the above, using data attributes to declarativly announce the behaviour within the markup. Behaviour is kept out of the view, but at a glance you can see what is happening.
因此,作为上述的第三种选择,使用数据属性来声明性地声明标记中的行为。行为被排除在视野之外,但您一眼就可以看到正在发生的事情。
Bootstrap example:
引导程序示例:
<button type="button" class="btn btn-lg btn-danger" data-toggle="popover" title="Popover title" data-content="And here's some amazing content. It's very engaging. Right?">Click to toggle popover</button>
Source: http://getbootstrap.com/javascript/#popovers
来源:http: //getbootstrap.com/javascript/#popovers
NoteThe main disadvantage with the second example is the pollution of global namespace. This can be circumvented by either using the third alternative above, or frameworks like Angular and their ng-click attributes with automatically scope.
注意第二个例子的主要缺点是全局命名空间的污染。这可以通过使用上面的第三种替代方法或像 Angular 这样的框架及其具有自动范围的 ng-click 属性来规避。
回答by Mark Pieszak - Trilon.io
<whatever onclick="doStuff();" onmouseover="in()" onmouseout="out()" />
onclick, onmouseover, onmouseout, etc.events are actually bad for performance(in Internet Explorermainly, go figure). If you code using Visual Studio, when you run a page with these, every single one of these will create a separate SCRIPT block taking up memory, and thus slowing down performance.
onclick、onmouseover、onmouseout 等事件实际上对性能不利(主要在Internet Explorer 中,如图)。如果您使用Visual Studio 进行编码,当您使用这些运行页面时,其中的每一个都会创建一个单独的 SCRIPT 块,占用内存,从而降低性能。
Not to mention you should have a separation of concerns: JavaScript and layouts should be separated!
更不用说您应该分离关注点:JavaScript 和布局应该分离!
It is always better to create evenHandlers for any of these events, one event can capture hundreds/thousands of items, instead of creating thousands of separate script blocks for each one!
为这些事件中的任何一个创建 evenHandlers 总是更好,一个事件可以捕获成百上千个项目,而不是为每个项目创建数千个单独的脚本块!
(Also, everything everyone else is saying.)
(另外,其他人都在说。)