javascript - 如何使用不同名称的 jquery 克隆生成 HTML?

标签 javascript jquery html clone

我有这样的 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") );
});

Above code is working but it is creating elements with same name .我想生成这样的东西:

<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;    
    });
});​

关于javascript - 如何使用不同名称的 jquery 克隆生成 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10800713/

相关文章:

javascript - 网格和动态表的高度

javascript - 如何在移动鼠标时对背景图像进行 3D 倾斜以改变视角?

javascript - jQuery 动画 : Change the destination of a prop during the animation

html - 从 component.html 文件加载 Bootstrap

javascript - 如何在 PHP if/else 语句中调用 JavaScript 文件?

javascript - CKFinder 弹出 onbeforeunload javascript

javascript - PDF JavaScript的执行条件

javascript - 在排序中使用选择值作为 Json Var

javascript - 如何在未找到结果时显示警报

html - 粘性页脚隐藏了我网站底部的内容