$('#filter').on('click', function(){
$('#sort').off('click');
console.log($(this));
});
$('#sort').on('click', function(){
$('#filter').off('click');
console.log($(this))
});
$('.close').on('click', function () {
console.log($(this));
$('#sort').on('click');
$('#filter').on('click');
});
如果上面的div具有相同的选择器id,为什么div .close
不将on方法返回给它们?
编辑:为了清楚起见,我想暂时删除两个元素中未点击的事件(#filter
或 #排序
)。然后点击'.close'
将使所述元素再次返回到on方法。
最佳答案
off()
并不像你想象的那样工作。它实际上删除了事件处理程序(回调函数),而不仅仅是隐藏它们,因此您无法使用简单的 on()
恢复它们,它们在 off 之后不再由元素存储()
,你必须重新添加它们。跟踪是否添加了事件处理程序并不容易,因此我建议采用另一种方法。
var sort = true;
var filter = true;
$('#filter').on('click', function(){
if (!filter)
return;
sort = false;
console.log($(this));
});
$('#sort').on('click', function(){
if (!sort)
return;
filter = false;
console.log($(this))
});
$('.close').on('click', function () {
console.log($(this));
sort = true;
filter = true;
});
使用 toggle()
并将其与 on()
和 off()
函数结合使用的另一种方法。嗯,我发现 jquery toggle()
与 dom 元素不是松散耦合的,所以你不能用它来做到这一点。您必须创建自己的实现,例如如下所示:
function toggle(options) {
var currentValue = !!options.value;
return function (value){
if (value === undefined)
value = !currentValue;
if (value != currentValue)
if (value) {
currentValue = true;
options.on();
}
else {
currentValue = false;
options.off();
}
};
}
通过此切换实现,您的代码将如下所示:
var switches = {
sort: toggle({
on: function (){
$('#sort').on('click', function(){
switches.filter(false);
console.log($(this))
});
},
off: function (){
$('#sort').off('click');
}
}),
filter: toggle({
on: function (){
$('#filter').on('click', function(){
switches.sort(false);
console.log($(this));
});
},
off: function (){
$('#filter').off('click');
}
})
};
$('.close').on('click', function () {
console.log($(this));
switches.sort(true);
switches.filter(true);
});
switches.sort(true);
switches.filter(true);
关于javascript - 交替选项卡上的开/关单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22072297/