2012-05-02 147 views
1

考虑下面的HTML的指标:jQuery的:如何获取列表元素

<ul> 
    <li class="imgThumbLi"> 
     <img src="larry.jpg"/> 
    </li> 
    <li class="imgThumbLi"> 
     <img src="curly.jpg"/> 
    </li> 
    <li class="imgThumbLi"> 
     <img src="moe.jpg"/> 
    </li> 
</ul> 

然后我有一些jQuery的处理每当有人对这些<img>元素之一悬停他们的鼠标:

$(".imgThumbLi").live({ 
    mouseenter: 
     function() { 
      // Obtain the source of the current image we're hovering over. 
      var src = $(this).children('img')[0].src; 

      // Now I need to know which <li> the "current" (one we're hovering 
      // over) image's parent <li> we're in, as a zero-based index 
      // of the <ul>. 
      var currListElementIndex = ???? 
     } 
    } 
); 

因此,如果用户悬停在larry.jpg上,那么currListElementIndex的值将为0。如果他们徘徊在moe.jpg以上,那么价值将是2,等等。

编辑:由于一些其他方面的限制,我不能ID添加到对<li>元素或做其他任何东西,是显而易见的......我需要获得<ul>某种方式(通过功能也许??),并找出哪些是<ul>我英寸

回答

3

由于直播功能的“礼”应用是指数,你可以使用$(本)的.index得到它的索引()。所以

var currListElementIndex = $(this).index()返回索引

0
$(".imgThumbLi").live({ 
    mouseenter: 
     function() {   
      var item=$(this); 
      var src = $(this).children('img')[0].src; 
      var currListElementIndex = item.index(); 
      alert(currListElementIndex); 
     } 
    } 
);