2010-03-08 121 views
0

鑑於下面顯示的html表和腳本我有一個問題,即鼠標輸入後鼠標離開事件發生,即使我不移動將鼠標移出該行。jquery:mouseleave事件似乎不應該觸發

<script type="text/javascript" language="javascript"> 
    function highlightRows(iMainID) 
    { 
     $('tr[mainid=' + iMainID+ ']').each(function() { 
      if ($(this).attr('old') == undefined) { 
       $(this).attr('old', $(this).css('backgroundColor')); 
      } 
      $(this).animate({ backgroundColor: "#FFFFCC" }, 500); 
      $(this).mouseout(function() { 
       if ($(this).attr('old') != undefined) { 
        $(this).animate({ backgroundColor: $(this).attr('old') }, 500); 
       } 
      }); 
     });   
    } 
</script> 
<table> 
    <tr> 
     <td mainid="1" onmouseover='highlightRows(1)'><div>text</div></td> 
     <td mainid="1" onmouseover='highlightRows(1)'><div>text</div></td>  
     <td mainid="2" onmouseover='highlightRows(2)'><div>text</div></td> 
    </tr> 
<table> 
+2

你真的不應該在「mouseover」處理程序中設置「mouseout」處理程序。事先分別設置這兩個處理程序,並使用jQuery而不是「onfoo」元素屬性來完成。 – Pointy 2010-03-08 19:01:46

+0

當我有重疊元素時,發生在我身上。計算機在兩個元件之間切換,並且這樣做非常快速地進入和離開。 – 2014-10-26 02:47:47

回答

2

由於Pointy和Jer都指出,您應該選擇一個模型(JQuery)或其他(無論在HTML中),不要混合它們。

最有可能的情況是,您的重複輸入與您多次訂閱同一活動的事實有關。 (如果你做了兩次鼠標懸停,你會得到兩個mouseout事件處理程序,它們都會被調用。)

另外,請注意重複的「mainid」值。這看起來像一個問題,可能是你的問題的原因。

+0

我需要重複的mainid值,因爲我想突出顯示包含相同mainid值的多行。 我在元素上使用onmouseenter屬性的唯一原因是因爲我的控件是使用ajax重新構建的,所以document.ready方法只是在開頭設置事件 – Jeremy 2010-03-08 19:22:48

+1

@Jeremy:您應該考慮使用JQuery的「live()」功能。從我所知道的情況來看,它們性能更好,並且可以讓你編寫更簡潔的代碼。 – 2010-03-08 19:25:26

+0

住()!謝謝,不知道那個。 – Jeremy 2010-03-08 20:04:12

0

你可能想要做這樣的事情:

function yourMouseOver(){...} 
function yourMouseOut(){...} 

有:

<td onmouseover="yourMouseOver()" onmouseout="yourMouseOut()">html</td> 

每次onmouseover事件被觸發是多餘的時間設置onmouseout事件。

1

jQuery的方式做這將是隻使用hover,在$(document).ready功能集和類似@pointy說放棄onmouseover一起

$(document).ready(function(){ 
    $('tr').hover(function() { 
     if ($(this).attr('old') == undefined) { 
      (this).attr('old', $(this).css('backgroundColor')); 
     } 
     $(this).animate({ backgroundColor: "#FFFFCC" }, 500); 
    }, function() { 
     if ($(this).attr('old') != undefined) { 
      $(this).animate({ backgroundColor: $(this).attr('old') }, 500); 
     } 
    }); 
}); 
+0

我在使用document.ready時遇到的問題是我的錶行在更新面板上更新了定時器,因此當文檔最初加載事件獲取集時,但在更新面板更新內容後,事件會丟失 – Jeremy 2010-03-08 19:26:04

1

爲什麼不使用.hover?

$('tr[mainid=' + iMainID+ ']').hover(
     function() 
     { 
      $(this).addClass('hoverClass'); 
     }, 
     function() 
     { 
      $(this).removeClass('hoverClass'); 
     } 
    ); 
+0

我必須同意,懸停事件讓它變得如此簡單。 – ryanulit 2010-03-08 19:12:27