JQuery clone and Onchange Events

JQuery clone and Onchange Events

本文关键字:Events Onchange and clone JQuery      更新时间:2023-09-26

我有一个包含行和input/select表单元素的表格。在底行,我有一个按钮可以向表格添加新行。最初,表格是空的,只有一行带有按钮
喜欢这个:

<form name="test" id="test" action="#" >
<table id="matrix">
  <tr id="1">
    <td><select class="parent" name="parent">
            <option value="C" label="C">C</option>
            <option selected="selected" value="P" label="P">P</option>
            <option value="B" label="B">B</option>           
        </select></td>        
    <td><div  id="my_data_1">
            <span title="parent_val"></span>
        </div></td>
    <td>&nbsp;</td>
  </tr>
  <tr >
    <td colspan="3"><input type="button" class="add_new" /></td>
  </tr>
</table>
</form>

现在,当我单击带有add_new类的按钮时,我克隆第一行,递增其id,然后将其插入最后一行上方。

问题是我有一个onchange事件附加到选择类父作为

$('#matrix').on('change', 'select.parent_type', function() {
    var RowID = $(this).closest('tr').attr('id');   
    var attributes_div = $('#matrix tr#'+RowID).find('div#my_data'+RowID );
    new_id = GetParentIDFormat(attributes_div, 3);
    $(attributes_div +"span[title='parent_val']").html(new_id);
});

当我添加两行或更多行时,更改函数会更改所有行的 SPAN "parent_val"值,而不是更改其 SELECT 父行的特定行。

有一些错误,没有GetParentIDFormat函数,我无法提供 100% 的解决方案,但这里是:

'select.parent_type'应该'select.parent'

$('#matrix tr#'+RowID).find('div#my_data');应该是
$('#' + RowID).find('.my_data'); .
请注意,您需要类,因为您不能有多个等效的 ID。


$(attributes_div +"span[title='parent_val']")
应该是 $("span[title='parent_val']", attributes_div)

结果是:

$('#matrix').on('change', 'select.parent', function() {
    var RowID = $(this).closest('tr').attr('id'); 
    var attributes_div = $('#' + RowID).find('.my_data');
    var new_id = GetParentIDFormat(attributes_div, 3);
    $("span[title='parent_val']", attributes_div).html(new_id);
});

attributes_div变量指向一个 jQuery 对象,因此您无法将其与字符串连接起来以获取选择器来选择所需的元素。相反,只需这样做:

attributes_div.find('span[title="parent_val"]').html(new_id);

这将在attributes_div引用的特定<div>中查找<span title="parent_val">元素,因此应该是您想要的单个元素。

但是,请注意,如果要克隆该行,则不能对所有<div>元素使用 ID my_data,因为它们应该是唯一的;请考虑改为更改为类。