一段代码胜过千言万语
// this is our dynamic created element.,
var $test = $('<button>If you add this event is working, if you remove this, and add again, event is not working...</button>');
// this is our event
$test.click(function(){
alert('Fooobar'); // fires only first time
});
// $test.on('click',function(){ <-- same behaviour
$('#add').click(function(){
$('#container').append( $test );
});
$('#remove').click(function(){
$('#container').html(''); // This is destroying all $test events!!!
});
我怎样才能删除元素,重新附加它并保存事件?
JS fiddle :
我想在不破坏事件的情况下删除元素。
最佳答案
我想你在找jQuery's detach method .
The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.
您可以在 $('#container').html('');
代码之前分离 $test
,这样 $test
就可以重新插入所有事件仍然附加。
关于javascript - jQuery 动态元素 - 如何删除元素并保存事件数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12448833/