0

我有一个表格,为了这个论坛,我已经简化了:

<form id="data0">
    <input id="name0" />
    <input id="address0" />
</form>

使用 jQuery 我需要 clone() ,然后将克隆表单的 id 更改为 name1、address1 等。

有没有办法在不单独更改它们的情况下做到这一点:

$('#data0').children('#name0').attr('id', 'name1');

就像遍历所有输入并将“0”更改为“1”一样。谢谢。

4

3 回答 3

2

您将首先使用.clone()jQuery 中的 api 来克隆表单#data0。然后迭代表单内部的输入元素,替换id并清除值,包括表单id。之后,将新表格放置到正文中。因此,您应该有一个计数器,用于在单击添加按钮时增加表单 ID。

以下示例使用data0表单作为克隆新表单的基础。

HTML

<input type="button" value="Add form" id="addBtn"/>

<form id="data0">
    <input id="name0" />
    <input id="address0" />
</form>

JavaScript

function ReplaceID(element, suffix) {
 var newId = $(element).attr('id').replace(/0/,suffix);
 $(element).attr('id', newId);
 $(element).val(newId); // for demo use, change to '' to reset value
}
var formNewId = 1;
$("#addBtn").on('click', function(){
    var newForm = $("#data0").clone();
    $('input', newForm).each(function(index,element){ // iterate input element inside the form
        ReplaceID(this, formNewId); // replace id

    }); 
    ReplaceID(newForm, formNewId); // replace the id of cloned form
    $("body").append(newForm);
    formNewId++;
});

工作示例:http: //jsfiddle.net/TfDUE/1/

于 2013-03-07T17:18:50.043 回答
0

像这个例子一样使用:

<form id="old">
    <textarea>Some Value</textarea>
    <input type="text" value="Some Value" />
    <input type="checkbox" value="bob" checked />
    <br />
</form>

<input type="button" value="Clone" id="clone" />

这个 jQuery 工作,包括 textareas:

$( 'input#clone' ).click(
    function()
    {
      $( 'form#old textarea' ).text( $( 'form#old textarea' ).val() )
      $("form#old").clone().attr( 'id', 'new_form' ).appendTo("body")

    }

  );
于 2013-03-07T17:18:25.347 回答
0

这是解决方案只需取出console.logand alert

$(":input").each(function() { //get all inputs

newId = $(this).attr('id');

   $(this).attr('id', newId.replace('0', '1')); 
    console.log($(this).attr('id'));
    alert($(this).attr('id'));
});

http://jsfiddle.net/yKZPK/

于 2013-03-07T17:37:03.593 回答