动态添加的表行不会触发点击事件 [英] Click event doesn't fire for table rows added dynamically

查看:112
本文介绍了动态添加的表行不会触发点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个空表,我通过jQuery添加行:

  $('#table& tbody:last')。append('< tr id ='+ symbol.Code1 +'>< td>'+ symbol.Code1 +'< / td>< td>'+ symbol.Code2 + '< / td>< td>'+ symbol.Code3 +'< / td>< / tr>') 

一切正常,但当我实施

  $(#table tr)click(function(e){
alert(this.id);
});

没有任何反应。

解决方案

您需要事件委托,您可以使用 on 来绑定动态添加元素的点击事件。 以点击方式绑定的方式将应用于现有元素,但不会应用于稍后添加的元素。

  $(document).on(click,#table tr,function(e){
alert(this.id);
});

您可以通过以下方式限制通过id或父类的父类选择器给出最接近的父选择器。

  $('。ParentElementClass' ,#table tr,function(e){
alert(this.id);
});

委派活动


委托活动的优点是,他们可以处理来自
子体的活动将在稍后添加到文档中。由
选择在
委托事件处理程序附加时保证存在的元素,您可以使用委派的事件到
,避免频繁附加和删除事件处理程序。 / p>


I have an empty table to which I'm adding rows via jQuery using:

$('#table > tbody:last').append('<tr id="' + symbol.Code1 + '"><td>' + symbol.Code1 + '</td><td>' + symbol.Code2+ '</td><td>' + symbol.Code3+ '</td></tr>');

Everything is OK but when I implement

$("#table tr").click(function(e) {
    alert(this.id);
});

nothing happens.

解决方案

You need event delegation you can use on to bind the click event for dynamically added elements. The way you are binding with click will apply on existing element but not elements which are added later.

$(document).on("click", "#table tr", function(e) {
    alert(this.id);
});

You can limit the scope for on by giving closest parent selector either by id or by class of parent.

$('.ParentElementClass').on("click", "#table tr", function(e) {
    alert(this.id);
});

Delegated events

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.

这篇关于动态添加的表行不会触发点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆