2016-12-22 54 views
-1

假設我有以下標記:如何解除綁定使用一種方法的jQuery中的事件?

<div class="button">1</div> 
<div class="button">2</div> 
<div class="button">3</div> 
<div class="button">4</div> 

我有以下的jQuery代碼:

$(".button").one('mouseenter', function() { 

    console.log("A button was pressed for the first time") 
    $(".button").on('mouseenter', function(){ 
     console.log("One button has already been pressed once") 
    }) 

}); 

問題是一個事件附加到所有四個按鈕。因此,如果我將鼠標懸停在第一個按鈕上,然後再按第一個按鈕,那麼一切都很順利,但如果我在第一個鼠標懸停之後將鼠標懸停在第二個按鈕上,則會再次觸發一個方法。如果我可以這樣做:

$(".button").one('mouseenter', function() { 

    console.log("A button was pressed for the first time") 
    $(".button").on('mouseenter', function(){ 
     console.log("One button has already been pressed once") 
    }) 

    //Remove event attached with one method from all buttons 

}); 

這樣一個方法不會觸發多次。但jquery說附加事件on方法只能刪除。

那麼是否有任何方法來解除綁定使用一種方法的jQuery中的事件?

回答

4

one在這裏沒有爲你做任何事情,雖然使用它是無害的。

您刪除與one迷上處理程序,就像你做on迷上處理:通過調用off具有相同事件和相同處理程序(或使用事件命名空間等)。

所以你的情況,可能是最簡單的事情是:

function handleOnce() { 

    console.log("A button was pressed for the first time") 
    $(".button").off('mouseenter', handleOnce)    // <=== 
       .on('mouseenter', function(){ 
     console.log("One button has already been pressed once") 
    }) 

} 
$(".button").on('mouseenter', handleOnce); 
+0

我用'one',因爲我想在此之後同樣的事情,其他的懸停事件做一些事情上的第一懸停特殊。 – user31782

+0

@ user31782:是的,這對單個元素非常有用,但對於其中的一個元素來說卻不是那麼好,因爲它的「一次」效果是基於每個元素的。 –

+0

但是現在用你的方法,如果我從所有按鈕中刪除'one',那麼它應該可以正常工作。那麼你爲什麼說_這裏沒有爲你做任何事情? – user31782

0

無需附加使用.one的事件。以下代碼適用於每個按鈕,並且在其回調中,您可以在鼠標輸入時應用邏輯。

$(".button").on('mouseenter', function(){ 
    $(this) // is the button that was pressed 
}) 

是否有刪除事件的原因?我看不出爲什麼上面的代碼不適合你的情況。

如果你只希望事件,並應用了以下的邏輯,你可以解除綁定像這樣:

$(".button").on('mouseenter', function(){ 
    $(this) // is the button that was pressed 

    // your logic here 

    $(this).unbind('mouseenter') 
}) 
+0

不,不推薦使用'one'。這不像[很難檢查](http://api.jquery.com/one/)。 –

+0

我一定誤會了它的另一個功能,我有一段時間沒有用過jQuery。 –