将事件处理程序附加到动态生成的元素

时间:2019-04-16 16:26:00

标签: javascript jquery

我有以下HTML:

<button type="button" id="Button">Go</button>
<div id="validation"></div>

我正尝试通过以下方式将事件处理程序添加到动态生成的元素中:

单击按钮->在div #validation中生成元素X->将事件处理程序附加到元素X

$(document).ready(function(){
    ID = 1;

    $("#Button").click(function(){

        /*generate new div inside div #validation with id #validationID
        1st one would be #validation1
        it contains a form with name accepterID and a button with name refuserID
        1st ones would be accepter1 and refuser1*/
        var newline = `
                    <div id="validation${ID}">
                        <form name="accepter${ID}">
                            <input type="hidden" name="name" value="phoegasus">
                            <button type="submit" value="valider">
                        </form>
                        <button name="refuser${ID}">refuser</button>
                    </div>
                    `
        $("#validation").append(newline);

        /*attach event handlers to the generated elements
        1st iteration would attach handlers to accepter1 and refuser1 */

        $("#validation").on('submit',"form[name^='accepter"+ID+"']",function(e){
            $("#validation" + ID).remove();
            //remove div validationID after submitting form
        });

        $("#validation").on('click',"button[name^='refuser"+ID+"']",function(){
            $("#validation" + ID).remove();
            //remove div validationID
        });

        ID++;

    });
});

当我提交表单或单击生成的按钮时,我要删除包含它们的div。如果我按下按钮rejectr1,它应该删除div#validation1。

生成元素时,不会将处理程序附加到它们。

该代码在onclick事件中执行时不起作用,但是当我在导航器控制台中执行时,它起作用。

我尝试在ID为#validation的div上使用DOMSubtreeModified,但是没有用。

1 个答案:

答案 0 :(得分:0)

您可以通过在on函数的第二个参数中使用类(或其他元素)来对其进行管理。

为此,请勿在添加事件中声明事件监听器。

这是一个完整的示例:

$("#validation").on('submit',"form.validation-form",function(e){
  e.preventDefault();
  console.log('form', $(this).attr('data-id'), ' submitted');
});



$("#validation").on('click',"button.validation-refuser",function(){
  console.log('clicked on refuser for form ', $(this).attr('data-value'));
    //code
});

var ID = 1;
$('#my-adder').on('click', function () {
  $('#validation').append('<form name="accepter'+ID+'" class="validation-form" data-id="'+ID+'"><input type="text" placeholder="my text field" /><button class="validation-refuser" name="refuser'+ID+'" data-value="'+ID+'">Refuser button</button><button type="submit">SUBMIT</button></form>');
  ID++;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="validation">
  <form name="accepter0" class="validation-form" data-id="0">
    <input type="text" placeholder="my text field" />
    <button type="button" class="validation-refuser" name="refuser0" data-value="0">Refuser button</button>
    <button type="submit">SUBMIT</button>
  </form>
</div>

<button id="my-adder">ADD A FORM</button>

希望有帮助