Domanda

My case

$(".myElementWithSpecialActionHandler").click(function(){});

after the element was relocated, say insert to a different position of the page,

var content_from_table = from_table_obj.html(); 
var content_target_table = to_table_obj.html();

before the ajax call. And I put

from_table_obj.html(content_target_table); 
to_table_obj.html(content_from_table);" in the ajax response handler.

after that the event handler function stops working. So I have to do

// after DOM manipulation
// again >.<
$(".myElementWithSpecialActionHandler").click(function(){});

Is event delegation the only to solve this? Or are there better way to avoid the scenario at the first place?

EDIT : added "relocate" code

È stato utile?

Soluzione

What you're doing is deleting the element and creating it again (Don't know why). So it no longer is the same element and your event handler won't work.

In this case, yes, you should use event delegation:

$(document).on('click', ".myElementWithSpecialActionHandler", function(){});

EDIT:

You can use .appendTo() to add it to another place (maybe a hidden div or something). Or you could just appendTo() it to its destination but hide it until you ajax callback fires. I created a little jsfiddle to show you that appendTo() does not remove the event handler: jsfiddle

var divId = '#div2';
$('button').on('click', function() {
   $(this).appendTo(divId);
    divId = divId == '#div2' ? '#div1' : '#div2';
});

Hope this helps you.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top