的off()
不工作的方式,你THI NK。它實際上刪除了事件處理函數(回調函數),而不僅僅是隱藏它們,所以你不能用一個簡單的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);
@DhavalMarthak你還不如簡明扼要,只需使用' $(選擇器).click()' – royhowie
@Luxelin Yup ..也可以使用! :) –
有人實際上爲[this]寫了一個jQuery插件(http://stackoverflow.com/questions/1809275/suppress-jquery-event-handling-temporarily)。 – royhowie