jquery中index()方法的理解

1.$(this).index()的理解
$(selector).index()获得第一个匹配元素相对于其同级元素的 index 位置。例如: 

 
<!DOCTYPE html>
<html>
<head>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("ul li.hot").click(function(){
    alert($(this).index());
  });
});
</script>
</head>
<body>
 
<p>Click the button to get the index of the element with id="favorite", relative to the jQuery selector (class="hot"):</p>
<button>Get index</button>
 
<ul>
<li>Milk</li>
<li class="hot">Tea</li>
<li class="hot">Coffee</li>
</ul>
 
</body>
</html>
 
 


点击第一个拥有hot的li返回的index是1
而$(selector).index(element)获得元素相对于选择器的 index 位置。该元素可以通过 DOM 元素或 jQuery 选择器来指定。例如

 
<!DOCTYPE html>
<html>
<head>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("ul li.hot").click(function(){
    alert($(this).index('.hot'));
  });
});
</script>
</head>
<body>
 
<p>Click the button to get the index of the element with id="favorite", relative to the jQuery selector (class="hot"):</p>
<button>Get index</button>
 
<ul>
<li>Milk</li>
<li class="hot">Tea</li>
<li class="hot">Coffee</li>
</ul>
 
</body>
</html>
 
 


点击第一个hot的li返回的是index为0

posted on   .smile  阅读(294)  评论(0编辑  收藏  举报

努力加载评论中...

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示