jquery bind click和< a>之间的性能标签onclick [英] performance between jquery bind click and <a> tag onclick

查看:201
本文介绍了jquery bind click和< a>之间的性能标签onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Web应用程序,并使用相当多的JavaScript执行任务。我有很多标签,绑定与Jquery点击做一些工作,所以我有这样的代码:

I am developing a web application and using quite a lot of JavaScript doing tasks. I have quite some tags that are bound with Jquery click to do some jobs, so I have code like this:

html代码:

 <a href="#" id="id1">some content here</a>
 <a href="#" id="id2">some content here</a>
 ....

Jquery代码:

 $('#id1').click(function(){
     //do something here..
     return false;
 });

 $('#id2').click(function(){
     //do something else here..
     return false;
 });



)。

with this approach, when the script runs, jquery must look up the selectors (id1,id2, ect).

但是还有另一种避免查找选择器的方法,如下所示:

but there is another approach which avoid looking up selectors , this is as follow:

<a href="requireJs.htm" onclick="f1();return false">some content here</a>
<a href="requireJs.htm" onclick="f2();return false">some content here</a>

和js代码:

 function f1(){
     //do something here..
 });

 function f2(){
     //do something else here..
 });

哪种方法更好,考虑性能?感谢您的帮助。

which approach is better, considering performance? thanks for help.

推荐答案

实际的效果增益是通过只使用一个事件处理程序父元素,并且使用 event.target 捕获children元素生成的事件,因为默认情况下,JavaScript中的事件会浮动到最外层的parent。

The real performance gain is by using only one event handler attached to the parent element, and catch the children element generated event with event.target, since events bubble up by default in JavaScript to the outermost parent.

将连结换成div

<div id="parent">
 <a href="#" id="id1">some content here</a>
 <a href="#" id="id2">some content here</a>
</div>

只向其附加一个事件侦听器

Attach only one event listener to it

$('#parent').click(function(event){
    // event.target is now the element who originated the event
    $(event.target).doSomething();
});

这是一个大的增加速度,特别是在旧的浏览器,如IE,有很多事件。

This is a big increase in speed, expecially in older browsers such as IE, and when you start to have really many events.

在此查看示例

这篇关于jquery bind click和&lt; a&gt;之间的性能标签onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆