简体   繁体   中英

Target dynamically added element using jQuery

I know how to use evenet Delegation on jQuery. To listen an even on dynamically added element I have to use following..

$('body .some-class').on('click', '.dynamically_added_ele', function(){});

I understand it quite. Come to actual problems. Suppose I have a button and DOM element which I want to add on document dynamically.

<button class="my-button">Click Me</button>
var newDom = '<p class="new-dom">Hello there I am new content</p>';

Now I am binding click event on button to create new element

var allow = true;
$('.my-button').on('click', function(){
    var newDom = '<p class="new-dom">Hello there I am new content</p>';
    if( allow ) {
       $(this).after($(newDom));
    } else {
        $(newDom).remove(); // Not removing the new added element. Can't target that newly added element
    }
    allow = false;
});

variable allow will check to be true then jQuery will create that element and last allow variable will be false . When again use click that button allow will be false and that time jQuery should remove the newly added element. But here I am facing the problems. I am not able to remove that newly added element like what I have coded above.

What can I do now?

I have to use class selector like this

var allow = true;
$('.my-button').on('click', function(){
    var newDom = '<p class="new-dom">Hello there I am new content</p>';
    if( allow ) {
        $(this).after($(newDom));
        allow = false;
    } else {
       $('.new-dom').remove();
       allow = true;
    }
 });

Maybe like this:

 var allow = true; var newDom = $('<p class="new-dom">Hello there I am new content</p>'); $('.my-button').on('click', function(){ if( allow ) { $(this).after(newDom); allow = false; } else { newDom.remove(); allow = true; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button class="my-button">Click Me</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM