1

我有这样的 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'>

jQuery:

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

什么是简单的解决方案。

谢谢

4

1 回答 1

2
$("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;    
    });
});​
于 2012-05-29T14:08:35.770 回答