关闭Live Elements失败

时间:2013-01-17 06:12:44

标签: javascript jquery

我试图使用JQuery的off函数解除附加到容器内元素的所有事件,但它正在做一些奇怪的事情。

我的代码如下

<div id='container'>
<button id='test_btn'>Test</button>
<button id='live_btn_id1'>Action</button>
<button id='live_btn_id2'>Action</button>
</div>

$("#test_btn").on("click", function(){
$("#container").find("*").off();
});

$("#container").on('click', 'button[id^=live_btn]', function(event) { 
alert("hello");
});

结果是test_btn正确停止工作,但“动作”按钮继续工作。但是,如果我执行以下操作:

$("#container").off();

它按预期工作,但也删除了我附加到容器的东西。有这种奇怪行为的原因吗?

1 个答案:

答案 0 :(得分:1)

使用委托时,您绑定的是元素,而不是后代选择器。

所以你打电话给$("#container").on(...,你绑定到#container,而不是live_btn

<{1}}上的{p> .off没有意义,因为没有任何东西与它们绑定。

一种可能的解决方案是命名click事件:

live_btn