简体   繁体   English

动态表行创建的更改不会触发事件

[英]Event does not fire on change for dynamic table row creation

Here the first two rows are created manually in html, the 3rd row is created dynamically. 在这里,前两行是使用html手动创建的,第三行是动态创建的。 Toggle does not work on the dynamically created row. 切换不适用于动态创建的行。

$(document).ready(function() {
 $('input:checkbox').on("change", function(e) {
    if ($(this).is(":checked")) {
        $(this).closest('tr').find("td.rowC .check").prop("disabled", false);
    } else {
        $(this).closest('tr').find("td.rowC .check").prop("disabled", true);
    }
});});

在此处输入图片说明

You should bind the toggle event to all dynamically created elements. 您应该将toggle事件绑定到所有动态创建的元素。 Apply your on("change", ... ) code to all 'input:checkbox' elements in your manually created rows after they are created. 创建手动行后on("change", ... )将其on("change", ... )代码应用于所有'input:checkbox'元素。

You should try out jquery event delegation. 您应该尝试使用jquery事件委托。 The idea behind it is to set the event on a parent element that will always be there (not dynamically added) and then filter it based on the child selector. 其背后的想法是将事件设置在始终存在(不会动态添加)的父元素上,然后根据子选择器对其进行过滤。 The code you are running sets up the events ONCE and those elements are later added, thus they don't have change handlers set up. 您正在运行的代码将事件设置为ONCE,然后又添加了那些元素,因此它们没有设置更改处理程序。

https://learn.jquery.com/events/event-delegation/ https://learn.jquery.com/events/event-delegation/

It is not working because the 3rd-row elements were not present in the document at the time of event binding. 它不起作用,因为在事件绑定时文档中不存在第三行元素。

You should use "live" (in case of jquery <= 1.7 http://api.jquery.com/live/ ) or $(document).on('click', 'input:checkbox', function(){}); 您应该使用“实时” (在jquery <= 1.7 http://api.jquery.com/live/的情况下)$(document).on('click', 'input:checkbox', function(){}); ( jquery > 1.7 Alternative to jquery live that can work ) (jquery> 1.7 可以替代有效的jquery live

use event delegation and change your event binding from 使用事件委托并从以下位置更改事件绑定

 $('input:checkbox').on("change", function(e) {

to

 $(document).on("change",'input:checkbox', function(e) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM