add event to element dynamically added inside ifra

2019-09-07 19:21发布

问题:

i have an HTML code like this

<iframe id="myframe">
    <ul>
        <li>
            <a href="" class="add-section">add section</a>
            <div>...</div>
        </li>
     <ul>
</iframe>

when the "add-section" link is clicked the parrent <li> that contains this (add-section) link get duplicated and inserted after, and the code become like this.

<iframe id="myframe">
    <ul>
        <li>
            <a href="" class="add-section">add section</a>
            <div>...</div>
        </li>
        <li>
            <a href="" class="add-section">add section</a>
            <div>...</div>
        </li>
     <ul>
</iframe>

i use this jquery code to achieve this and it works just fine.

$($("#myframe").contents().find('.add-section')).on("click",function(e){
    e.preventDefault();

    $(this).parent().after("<li>"+$(this).parent().html()+"</li>");

});

My problem is when i click in the new created (add-section) link the code won't execute.

My question is how to add a click event to the newest added element inside the iframe.

Thanks in advance.

回答1:

Try to bind the event to the body element and then use event delegation like

$("#myframe").contents().find('body').on("click", '.add-section', function (e) {
    e.preventDefault();
    $(this).parent().after("<li>" + $(this).parent().html() + "</li>");
});