簡體   English   中英

如何在jQuery中取消綁定“懸停”?

[英]How do I unbind “hover” in jQuery?

如何在jQuery中取消綁定“懸停”?

這不起作用:

$(this).unbind('hover');

$(this).unbind('mouseenter').unbind('mouseleave')

或者更簡潔(感謝@Chad Grant ):

$(this).unbind('mouseenter mouseleave')

實際上, jQuery文檔比上面顯示的鏈接示例有更簡單的方法(盡管它們可以正常工作):

$("#myElement").unbind('mouseenter mouseleave');

在jQuery 1.7中,你還可以使用$.on()$.off()事件的結合,所以要取消綁定懸停事件,你可以使用簡單,整潔的:

$('#myElement').off('hover');

偽事件名稱“懸停” 用作 “mouseenter mouseleave” 的簡寫 ,但在早期的jQuery版本中處理不同; 要求您明確刪除每個文字事件名稱。 使用$.off()現在允許您使用相同的速記刪除兩個鼠標事件。

編輯2016:

仍然是一個受歡迎的問題,所以值得注意@ Dennis98在下面的評論中的觀點,在jQuery 1.9+中,“懸停”事件被棄用 ,支持標准的“mouseenter mouseleave”調用。 所以你的事件綁定聲明現在應該是這樣的:

$('#myElement').off('mouseenter mouseleave');

單獨取消綁定mouseentermouseleave事件,或取消綁定元素上的所有事件。

$(this).unbind('mouseenter').unbind('mouseleave');

要么

$(this).unbind();  // assuming you have no other handlers you want to keep

unbind()不適用於硬編碼的內聯事件。

因此,例如,如果你想從<div id="some_div" onmouseover="do_something();">取消綁定鼠標懸停事件,我發現$('#some_div').attr('onmouseover','')是一種快速而骯臟的方式來實現它。

另一個解決方案是.die()用於附加.live()的事件。

例:

// attach click event for <a> tags
$('a').live('click', function(){});

// deattach click event from <a> tags
$('a').die('click');

你可以在這里找到一個很好的參考: 探索jQuery .live()和.die()

(抱歉我的英文:“>)

您可以使用off刪除on附加的特定事件處理程序

$("#ID").on ("eventName", additionalCss, handlerFunction);

// to remove the specific handler
$("#ID").off ("eventName", additionalCss, handlerFunction);

使用它,您將只刪除handlerFunction
另一個好的做法是為多個附加事件設置nameSpace

$("#ID").on ("eventName1.nameSpace", additionalCss, handlerFunction1);
$("#ID").on ("eventName2.nameSpace", additionalCss, handlerFunction2);
// ...
$("#ID").on ("eventNameN.nameSpace", additionalCss, handlerFunctionN);

// and to remove handlerFunction from 1 to N, just use this
$("#ID").off(".nameSpace");

所有懸停在幕后都是綁定到mouseover和mouseout屬性。 我會將這些事件單獨綁定和取消綁定。

例如,假設您有以下html:

<a href="#" class="myLink">Link</a>

然后你的jQuery將是:

$(document).ready(function() {

  function mouseOver()
  {
    $(this).css('color', 'red');
  }
  function mouseOut()
  {
    $(this).css('color', 'blue');
  }

  // either of these might work
  $('.myLink').hover(mouseOver, mouseOut); 
  $('.myLink').mouseover(mouseOver).mouseout(mouseOut); 
  // otherwise use this
  $('.myLink').bind('mouseover', mouseOver).bind('mouseout', mouseOut);


  // then to unbind
  $('.myLink').click(function(e) {
    e.preventDefault();
    $('.myLink').unbind('mouseover', mouseOver).unbind('mouseout', mouseOut);
  });

});

我發現這可以作為.hover()的第二個參數(函數)

$('#yourId').hover(
    function(){
        // Your code goes here
    },
    function(){
        $(this).unbind()
    }
});

第一個函數(.hover()的參數)是mouseover並將執行您的代碼。 第二個參數是mouseout,它將解除懸停事件與#yourId的綁定。 您的代碼只會執行一次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM