简体   繁体   中英

Delegate onclick handler of one element from another using Jquery

My question is as follows:

I have a dynamically generated element that has onclick='removeMe()', a function that causes it to removes itself.

I used jQuery .on('click',selector,handler) delegation to bind a function to this element, to execute a specific block of code.

However, the element removes itself and in doing so deletes the handler that would execute that block of code.

To spice things up: the block of code must be run after the element is removed, and I cannot edit the function that removes the element to execute my code after.

I'm new to jQuery, so the first solution that popped into my head was to somehow bind the handler to another element that is never removed, which runs when the first element is clicked. Is that possible?

Are there any other, better solutions I haven't thought of? Am I missing something obvious?

If my explanation is not clear I can provide clarification or provide the actual situation in which this takes place.

Thanks in advance!

Edit: Answered by Sivapriyan, and that solution is exactly what I needed. Thank you!

$(document).on("click",".selector",function(){
  alert("I will always live");
});

Declare in that way and you handler will always a live. Now the handler is on the document and no on the $element

Why don't you just run everything in your onClick handler.

$( "#target" ).click(function() {
    $(this).remove();
    //Execute your block of code :)
});

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