防止绑定到元素父级的函数触发

时间:2014-02-18 12:06:12

标签: javascript jquery

我有一个无序列表,当用户点击它时,会附加一个包含输入和锚标记的列表项。

然后当用户点击锚点时,我想执行一个功能。但是,当前绑定到无序列表的函数在锚点函数之前触发。

示例:

$('ul').on('click', function(e){
    console.log('this always fires first even when i only click the <a/>');
    // function to create the list item containing the input and link
  });

$(document).on('click', 'input, a', function(e){
    console.log('this fires second');
    e.preventDefault(); 
    e.stopPropagation(); // doesnt seem to do anything, the ul's function still fires
  });

我知道我可以通过使用.off方法防止ul的功能被触发,但这意味着我每次都必须解绑并重新绑定。

有更好的方法可以做到这一点,还是应该使用.off方法?

2 个答案:

答案 0 :(得分:2)

我认为将input, a次点击委托给文档是罪魁祸首;当它到达该节点时,ul上的事件已被触发。尝试从ul本身委派第二个事件,也可以使用stopImmediatePropagation()

无论如何,关于JSfiddle的一个例子会有所帮助。

答案 1 :(得分:0)

而不是针对document注册事件,而是尝试将其直接添加到ul元素。像这样:

$('ul').on('click', function (e) {
    console.log('this always fires first even when i only click the <a/>');
    // will not be fired
});

$('ul').on('click', 'input, a', function (e) {
    console.log('this fires first!');
    e.preventDefault();
    e.stopPropagation(); // now works
});

Here is a working example