2013-07-03 47 views
3

我有一個.on('click','td', function(){})事件。 我把它變成.off('click','td')。我現在想再次.on()同一個事件。 我嘗試了一些.on()的組合,它沒有工作。可以通過將它分配給一個變量來完成,但不知道該怎麼做。.on().off()後的jQuery事件

+1

[我不能複製此問題](http://jsfiddle.net/UcHj9/) – Ohgodwhy

+0

做我必須再次定義整個函數?我想要.on()之前定義的事件。可以通過將它分配給一個變量來完成,但不知道如何做到這一點。 – change

回答

6

把事件處理函數中的變量,並像這樣使用它:

var handler = function(e){ 
    //code here 
} 

//on 
$('#myselector').on('click', handler); 

//off 
//Try this, this will only turn 'handler' off 
$('#myselector').off('click', handler); 

//If the above doesn't work, then try this 
//This will turn off all your other click handlers for the same element, 
//if for some reason turning off a particular handler doesn't work! 
$('#myselector').off('click'); 

//on again 
$('#myselector').on('click', handler); 
4

我假設點擊TD試試這個: 首先讓你的td一個類來判斷它是否打開或關閉。默認情況下,TD將擁有td-off類,如下所示:

<td class="td-off"> 

然後設置您的事件以更改類。

.on('click','td',function(){ 

    if($(this).hasClass('td-off')){ 
    $(this).removeClass('td-off'); 
    $(this).addClass('td-on'); 
    }else{ 
    $(this).removeClass('td-on'); 
    $(this).addClass('td-off'); 
    } 

}); 

然後最後設定的事件您開或者關

$('.td-on').click(function(){ 
    //Your event on 
}); 

$('.td-off').click(function(){ 
    //Your event off 
}); 

它可能不是最好的答案,但我希望你的想法

+0

不知道爲什麼我沒有想到它。讓我試試看,應該工作。 – change