使用 jquery 生成动态表单

Generating dynamic form with jquery

我在动态生成表单时遇到问题。 这是我的代码:

    <script>
    $(document).ready(function(){
        $('#add').on('click',function(){
            $('<p><input type="text"  id="testo"/><input type="button" name="remove" id="remove" Value="rimuovi" /></p>').appendTo(content);

        });

        //$('#remove').on('click', function() { 
            //$(this).parents('p').remove();
        //});
        $( 'body' ).on( "click", "#remove", function() {

            console.log( $( this ).text() );

        });
    });
    </script>
</head>
<body>
    <div id="content">
        <p>
            <input type="text" value="" placeholder="Input Value"/>
            <input type ="checkbox"  ></input>
            <input type="button" name="remove" id="remove" Value="rimuovi"></input>
            <input type="button" name="add" id="add" Value="add"></input>
        </p>
    </div>

</body>

添加字段效果很好,甚至删除按钮也是静态编写的。问题出在 jquery 生成的按钮 "remove" 上。它不起作用,也不会在控制台上生成任何输出。谢谢!

试试这个:您多次使用相同的 id。要么使用独特的 id,要么使之成为 class。看下面的代码

    $(document).ready(function(){
            $('#add').on('click',function(){
                $('<p><input type="text"  id="testo"/><input type="button" name="remove" class="remove" Value="rimuovi" /></p>').appendTo(content);

            });

            //$('#remove').on('click', function() { 
                //$(this).parents('p').remove();
            //});
            $( 'body' ).on( "click", "input[type='button'].remove", function() {

                console.log( $( this ).text() );

            });
  });

    $(document).ready(function() {
      $('#add').on('click', function() {
        $('<p><input type="text"  id="testo"/><input type="button" name="remove" id="remove" Value="rimuovi" /></p>').appendTo(content);

      });

      $(document).on('click', '#remove', function() {
        $(this).parents('p').remove();
      });
      $('body').on("click", "#remove", function() {

        console.log($(this).text());

      });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
  <p>
    <input type="text" value="" placeholder="Input Value" />
    <input type="checkbox"></input>
    <input type="button" name="remove" id="remove" Value="rimuovi"></input>
    <input type="button" name="add" id="add" Value="add"></input>
  </p>
</div>

这是代码

您需要 运行 单击文档以获取动态加载的元素