开发者

How to use jQuery live() to bind multiple events to all table rows after adding additional rows?

I'm trying to bind three events开发者_运维知识库 to one selector using the live() method, but I can't seem to get it working.

Here's what I have so far, and it works until I add additional table rows:

$("tr:has(td)").live('click',function(event){
      //do stuff
}).live('mouseover',function(){
    $(this).toggleClass('highlight');
}).live('mouseout',function(){
    $(this).toggleClass('highlight');
});

Once I add additional table rows, only the click event works. How can I get all three events to work after adding table rows?


In your example you're adding a live() on something that is not the object you want by going live().live().live() . This is the way jQuery handles chaining.

What you need to do is :

var $o = $("tr:has(td)");
$o.live('click',function(event){
      //do stuff
});
$o.live('mouseover',function(){
    $(this).toggleClass('highlight');
});
$o.live('mouseout',function(){
    $(this).toggleClass('highlight');
});

Here is an article on chaining


I think you have to do $("tr:has(td)").live() three times - you can't chain it.


Instead of using live() you can use event delegation, which is much more elegant:

$('table').hover(function(e) {
    $(e.target).closest('tr').addClass('highlight');
}, function(e) {
    $(e.target).closest('tr').removeClass('highlight');
})
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜