本文介绍了在< tr>< td>中的jquery克隆选择元素.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想克隆一个选择并更新name
和id
值.选择位于<tr><td>
I would like to clone a select and update the name
and id
values. The select is within a <tr><td>
<table>
<tr id="tr_1">
<td id="td_1">
<select name="tech_1" id="tech_1">
<option value="0">Please Select</option>
<option value="1">Mango</option>
<option value="2">Apple</option>
<option value="3">Banana</option>
<option value="4">Orange</option>
</select>
</td>
</tr>
</table>
<input type="button" id="btnClone" value="Clone" />
我可以在没有表的情况下做到这一点,但是我的挑战是将克隆放入新的<tr><td>
... </td></tr>
I can do it without the table, but my challenge is putting the clone within a new <tr><td>
... </td></tr>
这是我的jquery:
Here is my jquery:
$("#btnClone").bind("click", function () {
// get the last SELECT which ID starts with ^= "tech_"
var $tr = $('tr[id^="tr_"]:last');
// get the last SELECT which ID starts with ^= "tech_"
var $select = $('select[id^="tech_"]:last');
// Read the Number from that SELECT's ID (i.e: 3 from "tech_3")
// And increment that number by 1
var num = parseInt( $select.prop("id").match(/\d+/g), 10 ) +1;
// Clone it and assign the new ID (i.e: from num 4 to ID "tech_4")
var $klon = $select.clone().prop('id', 'tech_'+num ).prop('name', 'tech_'+num );
// Finally insert $klon wherever you want
$tr.after("<tr><td>").after($klon).after("</td></tr>");
});
此代码将导致克隆的<select>
低于原始代码,并且在新的<tr><td>
和</td></tr>
This code results in the cloned <select>
below the original and nothing between the new <tr><td>
and </td></tr>
推荐答案
在创建tr
和td
之后,尝试append
select元素,
Try to append
the select element after creating the tr
and td
,
$tr.after($("<tr><td></td></tr>").find("td").append($klon).end());
这篇关于在< tr>< td>中的jquery克隆选择元素.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!