单元上的单击事件(仅在悬停时显示)未触发
问题描述:
单击某个元素时,我无法触发某个事件,并且此元素仅在悬停td元素时才会显示。单元上的单击事件(仅在悬停时显示)未触发
//Hovering over a td element displayed a Span
$('td').hover(
function() {$(this).append('<span class="editCell">hello</span>')},
function() {$(this).find('span:last').remove()}
)
//Clicking on that span, it's supposed to trigger alert. But it doesn't.
$('.editCell').click(function(){
alert('hello');
})
答
因为.click()
事件不适用于动态添加的内容。
使用.on()代替
$("td").on("click", ".editCell" ,function(){
});
- 第一个参数是你要绑定的事件。
- 第二个参数是选择器,它过滤
td
中的所有元素,并仅将click
事件绑定到该选择器。 - 第三个参数是要调用的函数。
以上称为delegated-events
。
你也可以做这样的:
$(".editCell").on("click",function(){
});
答
这是因为editCell
元件页面加载之后被追加。您需要将事件委托给最近的静态元素。试试这个:
$("td").on("click", ".editCell", function() {
alert("hello");
});
的td
选择还是有点广泛,虽然,你应该把一个id上的editCell
最接近的父级的性能着想。