简体   繁体   English

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

[英]Attaching event handlers to dynamically generated elements

I have the following HTML : 我有以下HTML:

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

I'm trying to add event handlers to dynamically generated elements in the following way : 我试图通过以下方式将事件处理程序添加到动态生成的元素中:

Click button -> Generate element X inside div #validation -> Attach event handler to element X 单击按钮->在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++;

    });
});

When I submit the form or I click the generated button I want to remove the div that contains them. 当我提交表单或单击生成的按钮时,我要删除包含它们的div。 If I press the button refuser1, it should delete the div #validation1. 如果我按下按钮rejectr1,它应该删除div#validation1。

When the elements are generated the handlers aren't attached to them. 生成元素时,处理程序不会附加到它们。

The code doesn't work when it's executed during the onclick event but when I execute it in the navigator console it works. 该代码在onclick事件中执行时不起作用,但是当我在导航器控制台中执行时,它起作用了。

I tried using DOMSubtreeModified on the div with id #validation, but it didn't work. 我尝试在ID为#validation的div上使用DOMSubtreeModified,但是没有用。

you can manage it by using a class (or another element) in second argument of your on function. 您可以通过在on函数的第二个参数中使用类(或其他元素)来管理它。

For that, DO NOT declare your event listeners inside your add event. 为此,请勿在添加事件中声明事件侦听器。

This is a full working example : 这是一个完整的工作示例:

 $("#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> 

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将事件处理程序附加到JQuery生成的DOM元素 - Attaching Event Handlers to JQuery-generated DOM Elements 使用纯JavaScript将事件处理程序附加到使用类动态创建的元素上 - Attaching Event handlers to dynamically created elements with a class using plain JavaScript 难以将事件处理程序附加到动态生成的模态窗口元素 - Difficulty attaching event handler to dynamically generated modal window elements 将事件附加到动态创建的元素 - Attaching event to dynamically created elements 将处理程序(具有不同的操作)附加到多个生成的元素的最佳实践? - Best practice for attaching handlers (with different actions) to multiple generated elements? 在jQuery中附加事件监听器到动态生成的图像? - Attaching event listener to dynamically generated image in jQuery? 附加和重新附加事件处理程序 - Attaching and reattaching Event Handlers 使用javascript在循环中注入元素并附加Click事件处理程序 - Injecting elements and attaching Click event handlers in a loop with javascript 将事件处理程序附加到尚未在DOM中的dojox DataGrid存储中的元素上 - Attaching event handlers to elements in a dojox DataGrid store that are not in the DOM yet 如何使用jQuery将事件处理程序附加到动态生成的DOM元素上? - How can I attach event handlers to dynamically-generated DOM elements using jQuery?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM