开发者

Do looping through items and adding handlers to it hurt performance

Does it hurt in performance when I loop through list-items and add a click-handler to a开发者_StackOverflow中文版ll separate items?

The reason I do this is because I would only like to make the list item clickable if it contains an hyperlink.

The code I'm currently using is:

$('ul.paginator li').each(function() {
  if ($('a', this).length > 0) {
    $(this).css('cursor', 'pointer');
    $(this).click(function() {
      location.href = $('a', this).attr('href');
    });
  }
});


I'm not sure how much it might hurt performance, but have you considered using a somewhat simplified jQuery selector:

$('ul.paginator li:has(a)').each(
    function(){
        $(this).css('cursor','pointer').click(
            function(){
                location.href = $(this).find('a').attr('href');
            });
    });

Incidentally, the performance would depend on the number of elements you're searching through more than anything else. Just a few and it's likely to be imperceptible, a few thousand and it will (probably) be noticeable.


Edited to reduce the expense of has():

$('ul.paginator li a').each(
    function(){
        var address = this.href;
        $(this).closest('li').css('cursor','pointer').click(
            function(){
                location.href = address;
            });
    });

This should be less expensive, as it will select only those a elements within an li, and then move up to affect that li element.


depends how many rows there are. If there are thousands of them, then yes. If there are a modest amount then not really enough to be noticeable.

An alternative approach would be to put the click handler on the element that contains the items, and then when a click event comes in, to use the data in the event passed to the handler to determine what to do. One handler.


Yes, it is better to use delegate with a proper selector that selects only the items you want.

There will be only one handler created and attached.

If you don't want to use has() than this will be enough (no need for multiple handlers):

$('ul.paginator').delegate('click', 'li', function() {
    var link = $('a', this);
    if (link.length > 0) {
        location.href = link.attr('href');
    }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜