0

I have a global flag variable. If this flag's value is true then I add a lot of <div>s to the DOM, otherwise nothing happens. After this I need to handle the click event on all of the previously added <div>s. I can't add the click handler immediately after I created the <div>s, because they are in different parts of the code, however the flag variable is still accessible. I add the click handlers this way:

$('.js-click').click(function() {
   //Handle the click. 
});

It doesn't matters if the <div>s were added previously or not, the code above will work in any case, however because I have the global flag variable, I could add a condition before the jQuery code, so it would execute only if the <div>s were created.

if(flag) {
   $('.js-click').click(function() {
      //Handle the click. 
   });
}

Does this makes any difference? Is there an amount of element or a type of jQuery selection where this condition would increase efficiency?

4

3 回答 3

4

你为什么不只使用事件冒泡而不担心它们何时添加?

$(document /*or a container element that holds them all*/).on("click", ".js-click", function() {
    //handle the click
});

这样做的好处是您不会一次完成向多个元素添加点击事件。

于 2013-09-16T12:19:57.707 回答
1

快速回答是:如果实际的选择器执行(通常非常快)对您来说不是问题,那么不需要标志测试。

如果性能可能有问题,那么添加标志测试肯定会有所帮助(但它会增加代码的相互依赖性,因此如果您重命名标志或更改与之相关的逻辑,此代码可能会停止工作,可以保留不被注意)。

于 2013-09-16T12:22:16.573 回答
0

+1 用于 epascarello 的事件冒泡解决方案。

还有几篇关于 JQuery 性能规则的好文章我觉得很有帮助:

jQuery 性能规则

立即提高 jQuery 性能的 10 种方法

于 2013-09-16T12:55:51.090 回答