2012-03-09 51 views
0

我在使用live元素的mouseenter時遇到問題。當我將鼠標懸停在用javacript添加的選定元素上時,不會觸發這些函數。如何mouseenter與活元素?

我添加的元素與此:

this.fixElements = function() { 
    $('.iconstarsdynamic.isgradeable:not(.touched)').each(function(){ 
     var $self = $(this), 
       $gradeLength = Math.round(parseInt($self.width())/$maxGrade*100)/100; 

     $self.addClass('touched'); 

     for ($i = 1; $i <= $maxGrade; ++$i) { 
      $('<span />', { 
       "class" : "grader", 
       "z-index" : $i, 
       "width" : ($gradeLength*$i)+'px' 
      }).attr('grade', $i).appendTo($self); 
     } 
    }); 
} 

我嘗試mouseenter本:

this.hover = function() { 
    $('.iconstarsdynamic.isgradeable') 
     .on('mouseenter', '.grader', function(){ 
      $(this).css('visibility', 'visible'); 
      console.log('over'); 
     }) 
     .on('mouseleave', '.grader', function(){ 
      $(this).css('visibility', 'hidden'); 
     }); 
} 

我的輸出是這樣的:

<span class="iconstarsdynamic isgradeable touched" title="Rated 0 out of 4"> 
    <span class="stars" style="width:0%;"></span> 
    <span class="grader" z-index="1" style="width: 9.25px; " grade="1"></span> 
    <span class="grader" z-index="2" style="width: 18.5px; " grade="2"></span> 
    <span class="grader" z-index="3" style="width: 27.75px; " grade="3"></span> 
    <span class="grader" z-index="4" style="width: 37px; " grade="4"></span> 
</span> 

問題是, mouseenter從不運行。爲什麼是這樣?如果我將mouseenter附加到.iconstarsdynamic.isgradeable,它就會有效,但這不是我想要的。我希望它附加到.iconstarsdynamic.isgradeable .grader

回答

0

mouseentermouseleave事件不會冒泡,因此不會像您使用的事件委託方法一樣工作。您應該使用mouseovermouseout(如果有的話,您可能需要照顧子孫的事件)。

+0

我試過'mouseover'和'mouseout',同樣的問題,沒有任何事情發生。 – Marwelln 2012-03-09 09:15:06

+0

是的,它的確如此:http://jsfiddle.net/x57Ec/。但是你是否試圖讓懸停的元素在懸停時可見? 'mouseover'事件只會觸發可見元素,否則你應該使用'opacity:0'來隱藏元素。 – 2012-03-09 09:30:30

+0

這些元素隱藏着'visibility:hidden',並不知道它沒有這個能力。謝謝。 – Marwelln 2012-03-09 09:37:31