0

我按照这个例子 如何使用jQuery动态添加表单元素

是否可以将表单元素动态添加到动态生成的表单中?

这是我的代码:

<html>
 <script src="jquery.js" type="text/javascript"></script>
 <script>
 $(document).ready(function () {
     $('#addRow').click(function () {
         $('<div/>', {
            'class' : 'extraPerson', html: GetHtml()
         }).hide().appendTo('#container').slideDown('slow');
     });
     $('#addAttribte').click(function () {
         $('<div/>', {
            'class' : 'extraAttribute', html: GetHtml1()
         }).hide().appendTo('#extraAttribute').slideDown('slow');
     });
 })
 function GetHtml() {
     var len = $('.extraPerson').length;
     var $html = $('.extraPersonTemplate').clone();
     $html.find('[name=firstname]')[0].name="firstname" + len;
     return $html.html();    
 }
 function GetHtml1() {
     var len = $('.extraAttribute').length;
     var $html = $('.extraAttributeTemplate').clone();
     $html.find('[name=attribute]')[0].name="attribute" + len;
     return $html.html();    
 }
</script>
<div class="extraPersonTemplate">
    <input class="span3" placeholder="First Name" type="text" name="firstname">
    <a href="javascript:void(0)" id="addAttribute">Add Attribute</a>
    <div id="extraAttribute"></div>
</div>
<div class="extraAttributeTemplate">
    <input class="span3" placeholder="Attribute" type="text" name="attribute">
</div>
<div id="container"></div>
<a href="#" id="addRow"><i class="icon-plus-sign icon-white"></i> Add another family member</p></a>
</html>

我意识到新添加的表单元素的名称会有问题,但此时我只想能够动态地将一行文本添加到动态生成的表单中。

编辑:对不起,忘了提到问题所在;该页面以“添加另一个家庭成员”的链接开始。这将添加extraPersonTemplate. 此模板还有一个“添加属性”链接,可向此新添加的字段添加一个额外的表单字段。

但是,当我单击“添加属性”时,我希望它会添加extraAttributeTemplate到动态添加的表单的底部,但没有任何反应。

4

1 回答 1

4

具体有两个问题。

  1. ID 应该是唯一的。每个人都有一个 id 的锚addAttribute是无效的,只有在 DOM 中找到的第一个元素才会绑定事件。一开始这不是问题,因为只有其中一个,但是一旦您开始添加其他家庭成员,以后确实会成为问题。

  2. 绑定在就绪处理程序中的事件仅绑定到代码执行时存在的元素。如果您要添加要绑定这些事件的新元素,则需要使用事件委托

    $(document).on('click', '.addAttribute', function() {
        // add an attribute here
        // I've changed from an ID to a class selector
        // you'll need to find a way to get a reference to the correct elements from a specific anchor
    });
    

我已经整理了一个演示,上面详细说明了更改。

于 2013-10-11T08:54:21.457 回答