简体   繁体   English

有没有办法写这个更短或更有效?

[英]Is there way to write this shorter or more efficient?

I have ten blocks of code like this, it is all for dynamically created content: 我有十个像这样的代码块,它全部用于动态创建的内容:

$(document).on('click', '.item' , function() {
    //... do something
});

$(document).on('click', '.element' , function() {
    //... do something different
});

Is there a way to write this shorter or more efficient? 有没有办法写这个更短或更有效?

You could cache your document selector. 您可以缓存文档选择器。

var $document = $(document);

$document.on('click', '.item' , function() {
    //... do something
});

$document.on('click', '.element' , function() {
    //... do something different
});

But that's about it. 但那是关于它的。

Edit: Contribute a test to my jsPerf if you want hard data. 编辑:如果您需要硬数据,请为我的jsPerf提供测试。

Unfortunately, it's not. 不幸的是,事实并非如此。 That's the only way because content inside the function is different 这是唯一的方法,因为函数内部的内容是不同的

One thing you could do is create a map between selectors and handlers: 您可以做的一件事是在选择器和处理程序之间创建一个映射:

var handlers = {
  '.item' : function() {
    //... do something
   },

  '.element' : function() {
    //... do something different
  }
}

Then you can assign the handlers in one swift iteration: 然后,您可以在一个快速迭代中分配处理程序:

var $doc = $(document); // no need to wrap the document each time
for (var selector in handlers) {
  if (handlers.hasOwnProperty(selector))
    $doc.on('click', selector, handlers[selector]);      
}

One more comment (see @ArunPJohny's comment), regarding efficiency. 关于效率的另一个评论(参见@ ArunPJohny的评论)。 If you can get away with assigning the handler to an element lower in the DOM tree (farther from document), you should. 如果您可以将处理程序分配给DOM树中较低的元素(远离文档),那么您应该这样做。 In this construct: 在这个结构中:

$(static).on('click', dynamic, f);

For each click event that reaches an element in the $(static) collection, the dynamic selector is matched to see if f should be triggered. 对于到达$(静态)集合中的元素的每个click事件,匹配动态选择器以查看是否应该触发f。 If static is the document, then all clicks in the page will be matched. 如果static是文档,则页面中的所有点击都将匹配。 If you can get a more specific element, less clicks will be matched. 如果您可以获得更具体的元素,则可以匹配更少的点击次数。 For clicks you might not notice a big difference, but events that are triggered faster (mousemove) may give you trouble. 对于点击,您可能不会注意到很大的差异,但更快触发的事件(mousemove)可能会给您带来麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM