gpt4 book ai didi

javascript - jQuery 动态元素 - 如何删除元素并保存事件数据?

转载 作者:行者123 更新时间:2023-11-30 18:19:32 25 4
gpt4 key购买 nike

一段代码胜过千言万语

// 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com