我正在尝试为用户输入编写取消按钮。用户双击项目后将能够对其进行编辑,并且取消按钮将允许用户取消操作。
代码的双击部分效果很好,因为会出现一个带有取消按钮的文本输入框。但现在由于 DOM 已更改,jQuery 不再选择新元素,因此当单击取消按钮时,不会触发该事件。为了说明这一点,代码如下:
<div id="main">
<ul class="todoList">
<li id="todo-1" class="todo">
<div class="text">New Todo Item. Doubleclick to Edit
</div>
<div class="actions"> <a href="#" class="edit">Edit</a></div>
</li>
</ul>
</div>
<小时/>
var currentTODO;
$('.todo').on('dblclick', function () {
$(this).find('a.edit').click();
});
$('.todo a').on('click', function (e) {
e.preventDefault();
currentTODO = $(this).closest('.todo');
});
$('.todo a.edit').on('click', function () {
var container = currentTODO.find('.text');
if (!currentTODO.data('origText')) {
// Saving the current value of the ToDo so we can
// restore it later if the user discards the changes:
currentTODO.data('origText', container.text());
} else {
// This will block the edit button if the edit box is already open:
return false;
}
$('<input type="text">').val(container.text()).appendTo(container.empty());
container.append(
'<div class="editTodo">' +
'<a class="cancel" href="#">Cancel</a>' +
'</div>');
});
// The cancel edit link:
$('.cancel').on('click', function () {
alert("oops");
});
或者在这里:http://jsfiddle.net/S7f83/42/
因此,我的问题是,在 DOM 更改后如何“绑定(bind)”事件?非常感谢
最佳答案
在您的示例中,事件绑定(bind)到绑定(bind)时存在的控件,并与选择器匹配。如果您希望将操作应用于新创建的控件,则应将事件绑定(bind)到文档
本身。由于它是最高级别的 DOM 元素,因此来自较低级别的所有事件都会向上传播到它。
在第二个参数中,您提供上下文,因此只有从该上下文接收到事件时,函数才会触发。
$(document).on('dblclick', '.todo', function () {
$(this).find('a.edit').click();
});
我不会引用你的整个代码,但你会从这个代码中得到想法。
鼓励将监听器绑定(bind)到文档,因为它不会创建与您拥有的控件一样多的绑定(bind),而只是一个顶级绑定(bind),它等待事件在 DOM 树上传播。有关优化的更多信息:http://24ways.org/2011/your-jquery-now-with-less-suck/
关于javascript - jQuery 1.9 中 DOM 更改后事件无法触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16114163/