开发者

How to empty() element but keep event handlers etc?

开发者 https://www.devze.com 2023-04-05 09:26 出处:网络
How can you empty an element and re-use the elements and keep event handlers etc.? http://jsfiddle.net/WrMbG/

How can you empty an element and re-use the elements and keep event handlers etc.?

http://jsfiddle.net/WrMbG/

<div></div>

var inp = $('<input type="text" 开发者_Python百科/>')
    .keydown(function(){
        alert('keydown');
    });

$('div').append(inp);
$('div').empty();
$('div').append(inp);

all event handlers and etc. is destroyed when you empty an element.. how can you avoid this?


Use detach on the child instead:

inp.detach();

If you have multiple elements

var saved = $("div").children().detach();

From the documentation on empty:

To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.


try .detach() -

$('div input[type="text"]').detach();


You might try using .live()

var inp = $('<input type="text" id="myinput" />'); 

$('#myinput').live('keydown', function(){
    alert('keydown');
});

$('div').append(inp);
$('div').empty();
$('div').append(inp);


Try using jQuery.live(), which searches for newly created elements (whereas keydown will just try elements that were created before the keydown handler was created).

<div></div>

var inp = $('<input type="text" />');

// edit: live won't work when chaining it, so attaching separately
$("input").live('keydown', function(){
    alert('keydown');
});

$('div').append(inp);
$('div').empty();
$('div').append(inp);

See here for more info.


Try this jsfiddle

When you create your inp variable, it's a unique jQuery object. If you want to use it multiple times, you need to clone it in order to be able to reuse it. Supply the true parameter to the clone() method to get a deep copy, include events.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号