克隆并更改classname +1和字段名称

时间:2014-08-11 15:34:41

标签: javascript jquery clone

我正在试图弄清楚如何克隆这个div,以便克隆版本将产品2作为其类名以及输入nams以具有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");
        });
});

感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

为什么不为了简单而设置计数器,并在每次添加新行(产品)时增加计数器。像这样:

$(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

希望这有帮助!

答案 1 :(得分:2)

我建议您使用product-1 ,product-2 and so on作为您的ID,并使用product作为您的班级名称。通过这样做,你可以得到这样的东西:

$("#addproduct").click(function(){
    var temp = $(".product").last().prop('id').split("-");
    $(".product").last().clone().appendTo("body");
    var result = parseInt(temp[1]) + 1;
    //assume this last product is the one that already added
    $(".product").last().prop("id", "product-"+result); 

});

另一种方式:

$("#addproduct").click(function(){
    var temp = $(".product").last().prop('id').split("-");
    var result = parseInt(temp[1]) + 1;
    var html = $(".product:nth-child(1)").html();
    $(".product").last().after('<div id="product-'+result+'" class="product">'+html+'</div>');
});

答案 2 :(得分:1)

编辑,更新(v3)

尝试

html(将1添加到属性name的末尾,即将notes1替换为notes

<input name="notes1" type="text" />

js(v3)

$(document).ready(function () {    
    $("#addproduct").on("click", function () {
        var clone = $("[class^=product]:last")
        .clone(false, false)[0].outerHTML.replace(/(\d)/g, function(a) {
          return parseInt(a) + 1
        });       
        $(clone).appendTo("body");
        // console.log($(clone).attr("class"));
    });
});

jsfiddle http://jsfiddle.net/guest271314/z2nxe84e/