重新附加input元素使其事件不会触发

时间:2014-09-15 19:50:45

标签: jquery

我有一个输入和一个附加到它的事件处理程序

var input = $(document.createElement('input'));
input.on('keypress', function (e) {
    alert('You pressed ' + e.which);
});

我把它附加到div上,一切正常。

$('div').append(input);

但是当我删除它然后重新附加它时,

$('div').html('removed')
$('div').append(input);

我的事件处理程序附加到输入不起作用!为什么以及如何解决它?

http://jsfiddle.net/laggingreflex/35p2hg2h/

1 个答案:

答案 0 :(得分:1)

不要通过消隐html来删除你的元素。使用.detach并保留事件:

http://jsfiddle.net/35p2hg2h/1/

input.detach();     // preserves the event handlers
$('div').html('Input removed. wait for it...')
setTimeout(function () {
    $('div').html('Input appended again, but now events dont fire :?') // actually, now
                                                                       // they will
    $('div').append(input);
}, 1000);

另见:

Differences between detach(), hide() and remove() - jQuery