Stu*_*io4 5 jquery replace clone
我意识到这个问题类似于之前被问过的一些问题而且我可能没有得到它,因为它是晚上9点,但是我想知道如何解决这个问题.我知道我哪里出错我只是不知道如何解决它:
我正在克隆一个包含4个选择框的表行,我想克隆id和名称,但是将id增加1.这就是我现在所拥有的.
$(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");
});
Run Code Online (Sandbox Code Playgroud)
问题是,它正在获取第一个选择的id和名称,并正确地递增id,但将其应用于所有选择,这不是我想要的.
为清楚起见,我正在克隆的行的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>
Run Code Online (Sandbox Code Playgroud)
希望有人可以指出我在哪里可怕的错!
非常感谢
@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) );
});
...
});
Run Code Online (Sandbox Code Playgroud)
令人惊讶的是,一个美好的夜晚睡觉,并在正确的方向轻推可以实现.
再次感谢.