这里的jQuery代码有区别吗?(is there a difference between the jquery code here?)

编程入门 行业动态 更新时间:2024-10-25 14:29:49
这里的jQuery代码有区别吗?(is there a difference between the jquery code here?)

这是代码块a

$('ul.filter li').each(function() { $(this).click(function(e) { //do something }); });

这里是代码块b

$('ul.filter li').click(function(e) { //do something });

不要这些做同样的事情吗? 这个比那个好吗? 哪一个更好/更快的方法? 我会假设块b,因为它有更少的代码,但我想在此确认,谢谢

Here is the code block a

$('ul.filter li').each(function() { $(this).click(function(e) { //do something }); });

Here is code block b

$('ul.filter li').click(function(e) { //do something });

Don't these do the same thing? is one better than the other? Which one is the better/faster method? I would assume block b since it has less code but I want to confirm it here, thanks

最满意答案

你看到的效果将是相同的,但在第一种情况下,每个li元素都会被分配一个新函数,因为您正在each回调中创建函数对象。

在第二种情况下,只存在一个事件处理程序的副本,这意味着它使用的内存总量较少(尽管这可能不可测量)。

在内部, click调用 (在jQuery 1.7中),它也通过each元素迭代元素 :

return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); });

许多jQuery方法就是这种情况(通常在文档中提到),所以通过让jQuery隐式地执行此操作来保存字符和内存。

The effect you see will be the same, but in the first case, every li element is assigned a new function, as you are creating the function object inside the each callback.

In the second case, there exists only one copy of the event handler, which means it uses less memory over all (although this is probably not measurable).

Internally, click calls on (in jQuery 1.7), which is iterating over the elements via each as well:

return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); });

This is the case with many jQuery methods (most often noted in the documentation), so you are saving characters and memory by letting jQuery implicitly do this.

更多推荐

本文发布于:2023-07-14 20:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1107218.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   代码   jQuery   code   jquery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!