Jquery 未触发元素上的单击事件(仅在悬停时显示)

Jquery 未触发元素上的单击事件(仅在悬停时显示),jquery,events,hover,Jquery,Events,Hover,我无法在您单击某个元素时触发事件,而该元素仅在您将鼠标悬停在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

我无法在您单击某个元素时触发事件,而该元素仅在您将鼠标悬停在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');
})
//将鼠标悬停在td元素上会显示一个跨度
$('td')。悬停(
函数(){$(this.append('hello')},
函数(){$(this.find('span:last').remove()}
)
//点击这个范围,应该会触发警报。但事实并非如此。
$('.editCell')。单击(函数(){
警惕(“你好”);
})

这是因为
editCell
元素是在页面加载后追加的。您需要将事件委托给最近的静态元素。试试这个:

$("td").on("click", ".editCell", function() {
    alert("hello");
});
td
选择器仍然有点宽泛,但是为了提高性能,您应该在最近的
editCell
父节点上放置一个id。

因为
.click()
事件对动态添加的内容无效

改用

  • 第一个参数是要绑定的事件
  • 第二个参数是选择器,它过滤
    td
    中的所有元素,并将
    click
    事件仅绑定到该选择器
  • 第三个参数是要调用的函数
上述事件称为
委托事件

您也可以这样做:

$(".editCell").on("click",function(){

});
$(".editCell").on("click",function(){

});