这是代码块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.
更多推荐
发布评论