2013-06-05 63 views
4

我意识到这个问题类似于之前已经问过的一些问题,可能我没有得到它,因为它晚上9点但我希望得到一个小指针如何解决这个问题。我知道我要去哪里错我只是不知道如何解决它:jquery克隆,替换id和名称属性中的数字

我克隆与4选择框的表行,我想克隆ID和名称,但增加了一个ID。这是我目前所掌握的。

$(document).on("click", "#new_item", function() { 
    var rowCount = $("#widget_location_options tbody>tr:last select").attr("id").match(/\d+/); 
    var rowCount1 = rowCount*1 + 1; 
    var row = $("#widget_location_options tbody>tr:last").clone(true); 
    $("select option:selected", row).attr("selected", false); 
    $("select", row).attr("name", $("select", row).attr("name").replace(/\d+/, rowCount1)); 
    $("select", row).attr("id", $("select", row).attr("id").replace(/\d+/, rowCount1)); 
    row.insertAfter("#widget_location_options tbody>tr:last"); 
}); 

的问题是,它采取的第一选择的ID &名称和正确递增ID,但它appying所有选择这不是我想要的。

为了清楚起见,这一行的HTML我克隆看起来像这样:

<tr> 
<td><select id="arr_widget_location[1][position_id]" name="arr_widget_location[1][position_id]"> 
<option value="value">label</option> 
</select></td> 

<td><select id="arr_widget_location[1][position_id]" name="arr_widget_location[1][position_id]"> 
<option value="value">label</option> 
</select></td> 

<td><select id="arr_widget_location[1][position_id]" name="arr_widget_location[1][position_id]"> 
<option value="value">label</option> 
</select></td> 

<td><select id="arr_widget_location[1][position_id]" name="arr_widget_location[1][position_id]"> 
<option value="value">label</option> 
</select></td></tr> 

希望有人能指出我要去哪里错得离谱!

非常感谢

+0

请设置jsfiddle –

回答

8

@Mark F,你给了我一个正确方向的提示 - 谢谢。实际的解决方案看起来像这样:

$(document).on("click", "#new_item", function() { 
    ... 

    $(row).find("select").each(function(){ 
     $(this).attr("name", $(this).attr("name").replace(/\d+/, rowCount1)); 
    }); 
    $(row).find("select").each(function(){ 
     $(this).attr("id", $(this).attr("id").replace(/\d+/, rowCount1)); 
    }); 


    ... 
}); 

惊人的是什么样的良好的夜间睡眠和向正确的方向微调可以实现。

再次感谢。

1

你选择,除了行的所有select元素,并改变所有的名字和ID。

$("select", row).attr("name", $("select", row).attr("name").replace(/\d+/, rowCount1)); 
$("select", row).attr("id", $("select", row).attr("id").replace(/\d+/, rowCount1)); 

它看起来像你试图让你克隆行,像这样在每个select

$(row).find("select").attr("name", $("select", row).attr("name").replace(/\d+/, rowCount1)); 
相关问题