3

I have the .blur() event bound to an element. Whenever I remove an element with $(elem).remove() method, the .blur event is triggered for the same element. Here is jsFiddle - to see the case click on the blue div and press any key.

Here is the code: HTML:

<div id="container"></div>
<ul id="tr"></ul>

CSS:

#container {
    width:100px;
    height:100px;
    background:blue;
    position:relative;
    cursor:pointer;

} JS:

$("#tr").on('keydown', '#ti', function() {
    $(this).remove();
});
$("#tr").on('blur', '#ti', function() {
    alert('blur is triggered');
});
$('#container').on('click', function() {
 var item = '<li id="ti" contenteditable="true"></li>';
 $("#tr").append(item);
 $("#ti").last().focus();
});

How can I prevent the .blur event if an element is removed? Or maybe how can I know that the event is triggered my element's deletion?

4

2 回答 2

6

unbind您可以在删除元素之前简单地调用-function。那应该可以解决您的问题。代码:

$(elem).unbind();

这将解除绑定到对象的任何操作。

于 2013-08-19T18:02:12.163 回答
4

在移除项目之前移除模糊事件

$("#tr").on('keydown', '#ti', function() {
    $(this).off('blur');
    $(this).remove();
});
于 2013-08-19T18:04:47.557 回答