如何在jquery中使用on转换悬停功能

时间:2012-10-22 03:44:54

标签: javascript jquery

我有这段代码

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

如何使用on

为新的dom元素转换此函数

2 个答案:

答案 0 :(得分:8)

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

但不推荐使用'hover'伪事件代替传递'mouseenter mouseleave',因此您应该直接使用mouseentermouseleave

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

或者像这样:

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

或者像这样短:

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

答案 1 :(得分:2)

我会这样做:

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

修改:您的问题不清楚,如果您需要代理,请查看其他答案。