2010-03-08 43 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