admin管理员组

文章数量:1287971

I have this code

$("td").hover(function(){
                $(this).find('a.btn').show();
                }, function(){
                $(this).find('a.btn').hide();
            })

How can i convert this function for new dom elements with on

I have this code

$("td").hover(function(){
                $(this).find('a.btn').show();
                }, function(){
                $(this).find('a.btn').hide();
            })

How can i convert this function for new dom elements with on

Share Improve this question asked Oct 22, 2012 at 3:44 MirageMirage 31.6k64 gold badges171 silver badges266 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 11
$("#mytable").on('hover', 'td', function(){
    $(this).find('a.btn').show();
    }, function(){
    $(this).find('a.btn').hide();
});

But using the 'hover' pseudo event as a substitute for passing 'mouseenter mouseleave' is deprecated, so you should really use mouseenter and mouseleave directly.

$("#mytable").on('mouseenter', 'td', function(){
    $(this).find('a.btn').show();
})
.on('mouseleave', 'td', function(){
    $(this).find('a.btn').hide();
});

Or like this:

$("#mytable").on({'mouseenter': function(){
    $(this).find('a.btn').show();
}, 'mouseleave': function(){
    $(this).find('a.btn').hide();
}}, 'td');

Or shorter like this:

$("#mytable").on('mouseenter mouseleave', 'td', function(e){
    $(this).find('a.btn').toggle(e.type === 'mouseenter');
});

I would do it like this:

$('td').on({
  mouseenter: function() { $(this).find('a.btn').show() }
  mouseleave: function() { $(this).find('a.btn').hide() }
})

Edit: It's not clear by your question if you need delegation in that case check out the other answer.

本文标签: javascriptHow to convert hover function with on in jqueryStack Overflow