You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery动态元素事件无响应?事件委托问题排查

解决动态添加行中按钮点击无响应的问题

核心问题:按钮事件未使用委托绑定

你当前的按钮点击事件是直接绑定在页面加载时已存在的.button_display元素上:

$(".button_display").on( "click", function() {              // Display the value of a row
    var selected_line = $(this).parents('tr').attr('data-row');
    var new_comment = $("#comment_"+selected_line).val();
    console.log('Value : ' + new_comment);
});

这种绑定方式仅对初始DOM中存在的元素生效,动态添加的新行按钮不会自动继承该事件。你需要像处理下拉框change事件那样,使用事件委托,将事件绑定到一个始终存在的父容器(比如document或表格的tbody),并指定目标选择器为.button_display:

$(document).on("click", ".button_display", function() {
    var selected_line = $(this).parents('tr').attr('data-row');
    var new_comment = $("#comment_"+selected_line).val();
    console.log('Value : ' + new_comment);
});

额外修复:动态生成行的ID语法错误

你添加新行的代码中,ID拼接存在语法错误:

$("#row_0").before('<tr id=&quot;row_&quot;'+selected_item+'&quot; data-row=&quot;'+selected_item+'&quot;>...');

这段代码会生成错误的ID(比如row_"3"),正确写法应调整引号位置:

$("#row_0").before('<tr id=&quot;row_'+selected_item+'&quot; data-row=&quot;'+selected_item+'&quot;><td><input type=&quot;text&quot; id=&quot;comment_'+selected_item+'&quot; value=&quot;Value '+selected_item+'&quot;></td><td><button type=&quot;submit&quot; class=&quot;button_display&quot;>Display</button></td></tr>');

修正后生成的ID会是row_3这类符合预期的格式。

优化建议:使用就近父元素作为委托容器

虽然绑定到document可以正常工作,但更推荐绑定到离目标元素最近的、始终存在的父元素(比如表格的tbody),减少事件冒泡层级,提升性能:

$("table tbody").on("click", ".button_display", function() {
    var selected_line = $(this).parents('tr').attr('data-row');
    var new_comment = $("#comment_"+selected_line).val();
    console.log('Value : ' + new_comment);
});

内容的提问来源于stack exchange,提问作者Olivier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 00:26:21