如何使用具有不同名称的 jquery 克隆生成 HTML

How to generate HTML with jquery clone with different names?

本文关键字:jquery HTML 何使用      更新时间:2023-09-26

我有这样的HTML:

<div id='main'>
   <div id='child-0'>
     <input type='text' name='data[0][name]'>
     <input type='text' name='data[0][dob]'>
     <input type='text' name='data[0][location]'>
   </div>
</div>
<input type='button' id='add' value='Add'>

j查询:

$("input#add").live( 'click', function(){
   $("#main").append("<br />");
   $("#child-0").clone(false).appendTo( $("#main") );
});

上面的代码正在工作,但它正在创建具有相同名称的元素。我想生成这样的东西:

<div id='main'>
   <div id='child-0'>
     <input type='text' name='data[0][name]'>
     <input type='text' name='data[0][dob]'>
     <input type='text' name='data[0][location]'>
   </div>
   <div id='child-1'>
     <input type='text' name='data[1][name]'>
     <input type='text' name='data[1][dob]'>
     <input type='text' name='data[1][location]'>
   </div>
</div>

什么是简单的解决方案。

谢谢

$("input#add").live( 'click', function(){
    $("#main").append("<br />");
    var cloned = $("#main div:last").clone(false).appendTo( $("#main") );
    cloned.find('[name^=data]').attr('name', function() {
        var index = this.name.match(/'[('d)']/);
        if (index != null && index.length > 1) {
            var newIndex = parseInt(index[1], 10) + 1; 
            return this.name.replace(/'[('d)']/, '[' + newIndex + ']');
        }
        return this.name;    
    });
});​