2014-02-07 133 views
1

我将事件绑定到两个ID一次。事实之后,有没有办法针对一个ID来解除绑定事件?解除绑定jquery事件

下面是我的代码的简化版本。一个事件在AJAX请求返回HTML模板后解绑/绑定...如果模板“AA”呈现,则第一个事件被绑定;如果模板'BB'呈现,则第二个脚本被绑定。

//Template AA 
$('#container').off('dblclick', '#store, #compare_store'); 
$('#container').on('dblclick', '#store, #compare_store', function(){ 
    console.dir('test1'); 
}); 

//Template BB 
$('#container').off('dblclick', '#store'); //This does not unbind the event listed as above 
$('#container').on('dblclick', '#store', function(){ 
    console.dir('test2'); 
}); 

/* Console Output When double-clicking '#store': 
    test1 
    test2 
*/ 

双击'#store'元素时,两个事件当前都被触发。期望的效果是让第二个事件解除绑定第一个事件(仅用于'#store'),并绑定一个新事件。

我知道,分别绑定每个ID将提供所需的结果。我也知道,使用课堂也可以完成这项工作。

预先感谢您!

+0

是否'off'功能的工作,如果你拆散了原来的选择'#store,#compare_store' ?我知道这不是你想要的,但我很好奇,如果这是jquery期望的工作。我真的不知道jquery如何处理,你可能需要单独绑定事件 – helion3

+0

你真的不能这样做,因为你必须传入完全相同的选择器来关闭()在'on()'中绑定事件。你可以命名空间的事件,但这不会帮助,因为你仍然不能删除一半的事件处理程序,当你删除这样的事件处理程序时,它是全部或没有。 – adeneo

+0

@ helion3:当使用“#store,#compare_store”时,它起作用,因为它是逐字的。 – ejc

回答

0

昌的选择,这样的off方法调用on选择匹配:

//Template AA 
$('#container').on('click', '#compare_store', function(){ 
    console.log("a", this); 
}).on('click', '#store', function(){ 
    console.log("b", this); 
}); 

//Template BB 
$('#container').off('click', '#store'); //This does not unbind the event listed as above 

http://jsfiddle.net/xzgnH/