开发者

How to bind to all click events, check for an attribute.... Efficiently?

I want to create a binding that captures all click events. And then if the item clicked has a "data-track" attribute do something...

What is the efficient way to do this? Can I bind at the body and let all the events bubble up. Any suggestions on 开发者_开发知识库how and how to do this efficiently?

Thanks


You should aim for simplicity over performance: Let jQuery do the work for you, and assume that the jQuery devs are better at optimizing JS than you unless you can prove otherwise.

Use the has attribute jQuery selector to setup a live click handler for all elements with the data-track attribute:

$('[data-track]').live('click', function () {

});


Attach click event handler at the document level using delegate with attribute selector [data-track].

$(document).delegate('[data-track]', 'click', function(){
   //Do something here
});


Why don't you bind click events to ONLY items with a data-track attribute?

$('[data-track]').click(function() {
    var data_track = $(this).attr('data-track');
    //code here
});


I would go like this:

$('*[data-track]').click(function(ev){
     // do something
});

or (if some such content coming from Ajax)

$('*[data-track]').live('click', function(ev){
    // do something 
});


Do you have to capture all click events? If you're only doing something if it has a "data-track" attribute, I believe you should be able to do:

$("*[data-track]").click(function(){//do something});

I'm not sure how that compares to other methods though for efficiency, although I think that since jQuery captures all events at the window level, it shouldn't make a difference.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜