1

我有这个代码

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

如何将此函数转换为新的 dom 元素on

4

2 回答 2

9
$("#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');
});
于 2012-10-22T03:46:53.027 回答
2

我会这样做:

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

编辑:如果您在这种情况下需要委托,您的问题不清楚,请查看其他答案。

于 2012-10-22T03:48:17.053 回答