【问题标题】:JQuery clone and Onchange EventsJQuery 克隆和 Onchange 事件
【发布时间】:2013-11-06 13:49:41
【问题描述】:

我有一个包含行和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 父级的特定行。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    有一些错误,没有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);
    });
    

    【讨论】:

      【解决方案2】:

      attributes_div 变量指向一个 jQuery 对象,因此您不能将其与字符串连接以获取选择器来选择您想要的元素。而是这样做:

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

      这将在attributes_div 引用的特定&lt;div&gt; 内查找&lt;span title="parent_val"&gt; 元素,因此应该是您想要的单个元素。

      但是,请注意,如果您要克隆该行,则不能在 所有 &lt;div&gt; 元素上使用 ID my_data,因为它们应该是唯一的;考虑改为类。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-20
        • 2010-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-07
        • 2015-05-18
        相关资源
        最近更新 更多