在jQuery 1.9中更改DOM后,事件无法触发

时间:2013-04-19 22:02:29

标签: javascript jquery dom

我正在尝试为用户输入编写取消按钮。用户可以在双击后编辑项目,取消按钮将允许用户取消操作。

代码的双击部分效果很好,因为文本输入框出现时附带了取消按钮。但是现在由于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发生变化后,如何“绑定”事件?非常感谢你

3 个答案:

答案 0 :(得分:4)

在您的示例中,事件绑定到绑定时存在的控件,并匹配选择器。如果您希望操作申请新创建的控件,则应将事件绑定到document本身。因为它是最高级别的DOM元素,所以来自较低级别的所有事件都将传播到它。

在第二个参数中,您可以给出上下文,因此只有从该上下文接收到事件时才会触发该函数。

$(document).on('dblclick', '.todo', function () {
    $(this).find('a.edit').click();
});

我不会引用你的整个代码,但是你会从这个代码中得到这个想法。

鼓励将侦听器绑定到文档,因为它不会创建与您拥有的控件一样多的绑定,只有一个顶级绑定,它等待事件在DOM树上传播。有关最优化的更多信息:http://24ways.org/2011/your-jquery-now-with-less-suck/

答案 1 :(得分:0)

使用

$('.todo').on('click', '.cancel', function () {
    alert("oops");
});

所以你将事件委托给现有元素( .todo

而不是

$('.cancel').on('click', function () {
    alert("oops");
});

答案 2 :(得分:0)

2种方法

在第二种情况下,我将事件委托绑定到最近的父节点,因此事件不需要冒泡到要执行的文档元素。这可以改善一些性能。取决于您是否想要将取消按钮放在其他地方的用途。

编辑:每个李有不同的ID,所以最好附加到班级.todo

$('.todo').on('click', 'a.cancel', function () { alert("oops"); });