[英]Can we have variables name in html, jQuery
我有以下結構
<tr>
<td data-unit="spear" class="tooltip">
<input type="text" size="2" name="spear-1" />
</td>
<td data-unit="sword" class="tooltip">
<input type="text" size="2" name="sword-1" />
</td>
</tr>
我希望每次我通過名稱中的 jQuery 變量調用克隆函數時都應該像spear-2. sword-2
一樣自動遞增spear-2. sword-2
spear-2. sword-2
這是一個例子,我有 20 個這樣的領域,我想要一個可以改變所有人的通用東西
這可能嗎?
試試這個簡單的示例代碼,如下所示:
html
<table>
<tr>
<td data-unit="spear" class="tooltip">
<input type="text" size="2" name="spear" />
</td>
<td data-unit="sword" class="tooltip">
<input type="text" size="2" name="sword" />
<input type="checkbox" name="knife" />
<select name="book">
<option>as</option>
</select>
</td>
</tr>
</table>
<button>click</button>
jQuery
$(document).ready(function () {
var a = 0;
$('button').click(function () {
a++;
var tr = $('tr').first().clone();
// inside find(), put any element you want to increment
// eg : .find('input, select, textarea')
$(tr).find('input, select').attr('name', function(i, e){
// i => index
// e => old value
// a => custom increment value
return e+'-' + a;
});
$(tr).appendTo('table');
})
});
演示- 檢查 Element(chrome) 以查看為新克隆的元素更改的屬性名稱。
此 Jquery 代碼可以幫助您克隆具有不同 ID 的 HTML 元素
<script type="text/javascript">
$(document).ready(function () {
var i = 2
$("#btnClone").click(function () {
$("#SpearClone").html($("#SpearClone").html() + '<input type="text" size="2" name="spear-' + i + '" />');
$("#SwordClone").html($("#SwordClone").html() + '<input type="text" size="2" name="sword-' + i + '" />');
i++;
});
});
</script>
<div id="DivClone">
<table>
<tr>
<td data-unit="spear" class="tooltip" id="SpearClone">
<input type="text" size="2" name="spear-1" />
</td>
<td data-unit="sword" class="tooltip" id="SwordClone">
<input type="text" size="2" name="sword-1" />
</td>
</tr>
</table>
<input type="button" id="btnClone" value="Call Clone" />
</div>
我希望我能幫助你......問候;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.