jquery中取消和綁定hover事件的正確方式

來源:互聯網
上載者:User

標籤:.com   說明文檔   out   官方   應該   read   沒有   and   jquer   

在網頁設計中,我們經常使用jquery去響應滑鼠的hover事件,和mouseover和mouseout事件有相同的效果,但是這其中其中如何使用bind去綁定hover方法呢?如何用unbind取消綁定的事件呢?
一、如何綁定hover事件
先看以下代碼,假設我們給a標籤綁定一個click和hover事件:
$(document).ready(function(){ $(‘a‘).bind({ hover: function(e) { //
Hover event handler alert("hover"); }, click: function(e) { // Click
event handler alert("click"); } }); });
當點擊a標籤的時候,奇怪的事情發生了,其中綁定的hover事件完全沒有反應,綁定的click事件卻可以正常響應。

但是如果換一種寫法,比如:
$("a").hover(function(){ alert(‘mouseover‘); }, function(){
alert(‘mouseout‘); })
這段代碼就可以正常的運行,難道bind不能綁定hover?

其實不是,應該使用 mouseenter 和 mouseleave 這兩個事件來代替,(這也是 .hover() 函數中使用的事件)
所以完全可以直接像這樣來引用:
$(document).ready(function(){ $(‘a‘).bind({ mouseenter: function(e) { //
Hover event handler alert("mouseover"); }, mouseleave: function(e) { //
Hover event handler alert("mouseout"); }, click: function(e) { // Click
event handler alert("click"); } }); });
因為.hover()是jQuery自己定義的事件,是為了方便使用者綁定調用mouseenter和mouseleave事件而已,它並非一個真正的事件,所以當然不能當做.bind()中的事件參數來調用。
二、如何取消hover事件
大家都知道,可以使用unbind函數去取消綁定的事件,但是只能取消通過bind綁定的事件,jquery中的hover事件是比較特殊的,如果通過這種方式去綁定的事件,則無法取消。
$("a").hover(function(){ alert(‘mouseover‘); }, function(){
alert(‘mouseout‘); })
取消綁定的hover事件的正確方式:
$(‘a‘).unbind(‘mouseenter‘).unbind(‘mouseleave‘);三、總結
其實,這些問題可以去參看jquery官方的說明文檔,只是很少有人去看過,網上的大多數教程只是講解如何去使用這個方法,達到目的即止,並沒有深入的瞭解為什麼這麼寫?

如果你有什麼疑惑,歡迎評論留言。


原文連結:http://www.uedsc.com/jquery-bind-hover-event.html

jquery中取消和綁定hover事件的正確方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.