对$(this).index()的一点见解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cometwo/article/details/52489724

参考:http://www.w3cfuns.com/notes/18316/5e6c82c28f4178fda5d628faa9317cd8.html

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <title>菜鸟教程(runoob.com)</title>
        <script type="text/javascript" src="js/jquery-2.1.4.js"></script>

        <script>
            $(document).ready(function() {
                $("h1").click(function() {
                    alert($(this).index());   //0,4,8
                });
            });
        </script>
    </head>

    <body>

        <h1 class="main">Coffee</h1>
        <p>哈哈哈哈哈哈哈</p>
        <p>哈哈哈哈哈哈哈</p>
        <p>哈哈哈哈哈哈哈</p>
        <h1 class="main">Milk</h1>
        <p>哈哈哈哈哈哈哈</p>
        <p>哈哈哈哈哈哈哈</p>
        <p>哈哈哈哈哈哈哈</p>
        <h1 class="main">Soda</h1>
        <p>哈哈哈哈哈哈哈</p>
        <p>哈哈哈哈哈哈哈</p>
        <p>哈哈哈哈哈哈哈</p>

    </body>

</html>

MD,还以为是jQuery BUG,修改

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <title>菜鸟教程(runoob.com)</title>
        <script type="text/javascript" src="js/jquery-2.1.4.js"></script>

        <script>
            $(document).ready(function() {
                $("h1").click(function() {
                    alert($(this).index('.main'));   //0,1,2
                });
            });
        </script>
    </head>

    <body>

        <h1 class="main">Coffee</h1>
        <p>哈哈哈哈哈哈哈</p>
        <p>哈哈哈哈哈哈哈</p>
        <p>哈哈哈哈哈哈哈</p>
        <h1 class="main">Milk</h1>
        <p>哈哈哈哈哈哈哈</p>
        <p>哈哈哈哈哈哈哈</p>
        <p>哈哈哈哈哈哈哈</p>
        <h1 class="main">Soda</h1>
        <p>哈哈哈哈哈哈哈</p>
        <p>哈哈哈哈哈哈哈</p>
        <p>哈哈哈哈哈哈哈</p>

    </body>

</html>

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());          //1,2
  });
});
</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

猜你喜欢

转载自blog.csdn.net/cometwo/article/details/52489724