我有一个简单的悬停功能,可以为LI添加关闭按钮。问题是,创建了新的LI并且悬停不再起作用。我知道.On();
会关注新创建的元素,但这似乎只适用于.click()
。
JS:
$("#sortable li").hover(function () {
$(this).find(".close").show();
},
function () {
$(this).find(".close").hide();
});
答案 0 :(得分:1)
您可以使用委托形式的事件处理,但它不能与伪事件hover
一起使用,因此您需要同时观察mouseenter和mouseleave事件。
$("#sortable").on("mouseenter", "li", function() {
// mouse over code here
$(this).find(".close").show();
});
$("#sortable").on("mouseleave", "li", function() {
// write your hover out code here
$(this).find(".close").hide();
});
或更紧凑的形式:
$("#sortable").on({
mouseenter: function() {
// mouse over code here
$(this).find(".close").show();
},
mouseleave: function() {
// mouse leave code here
$(this).find(".close").hide();
}
}, "li");
这样做的方式是鼠标事件冒充零件链,因此.on()
的委托形式会监视#sortable
父项,以查找源自子li
标记的事件,然后触发您的当它们与所需事件匹配时回调。
答案 1 :(得分:0)
$('#sortable').on({
mouseenter: function() {
$(this).find(".close").show();
},
mouseleave: function() {
$(this).find(".close").hide();
}
}, 'li');