문제

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.

다른 팁

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. If you can get away with assigning the handler to an element lower in the DOM tree (farther from document), you should. 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. If static is the document, then all clicks in the page will be matched. 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top