我正在尝试弄清楚如何克隆此 div,以便克隆版本将产品 2 作为其类名以及具有 rate2 和 notes2 的输入名称。
<div class="product1">
<input id="rate1" name="rate1" type="number">
<input name="notes" type="text">
<div>
尝试在此处追加 ****
<div class="sixteen columns" id="addproduct">
<label><i class="fa fa-plus-square"></i> Add another product</label>
</div>
============================================= ==================================
我对如何克隆它有一个粗略的想法,但就我所知,这就是这些。我看过其他帖子,但看不到一种简单的方法。
JQuery-
$(document).ready(function(){
$("#addproduct").click(function(){
$(".product1").clone().appendTo("body");
});
});
感谢您的帮助!
最佳答案
为了简单起见,您为什么不尝试保留一个计数器并在每次添加新行(产品)时递增它。像这样:
$(document).ready(function(){
// the counter:
var productID = 1;
// the click handler:
$("#addproduct").click(function() {
// clone last added product:
var nextProduct = $(".product" + productID).clone();
// add corresponding classes (remove old first):
nextProduct
.removeClass('product' + productID)
.addClass('product' + (++productID));
// update id and name to the first input:
nextProduct.find('input').eq(0).attr({
id: 'rate' + productID,
name: 'rate' + productID
});
// update name of the second input
nextProduct.find('input').eq(1).attr('name', 'notes' + productID);
// append to the body:
$('body').append(nextProduct);
});
});
这应该可以完成工作,尽管我建议为两个输入添加一些标识符(例如,不同的类名,这样您就可以避免使用 .eq()
表达式。
现场演示:http://jsbin.com/puluf/1/edit
希望这对您有所帮助!
关于javascript - 克隆并更改类名 +1 和字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25247021/