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

参考:http://www.w3cfuns.com/notes/18316/5e6c82c28f4178fda5d628faa9317cd8.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">Coffeeh1>
        <p>哈哈哈哈哈哈哈p>
        <p>哈哈哈哈哈哈哈p>
        <p>哈哈哈哈哈哈哈p>
        <h1 class="main">Milkh1>
        <p>哈哈哈哈哈哈哈p>
        <p>哈哈哈哈哈哈哈p>
        <p>哈哈哈哈哈哈哈p>
        <h1 class="main">Sodah1>
        <p>哈哈哈哈哈哈哈p>
        <p>哈哈哈哈哈哈哈p>
        <p>哈哈哈哈哈哈哈p>

    body>

html>

MD,还以为是jQuery BUG,修改


<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">Coffeeh1>
        <p>哈哈哈哈哈哈哈p>
        <p>哈哈哈哈哈哈哈p>
        <p>哈哈哈哈哈哈哈p>
        <h1 class="main">Milkh1>
        <p>哈哈哈哈哈哈哈p>
        <p>哈哈哈哈哈哈哈p>
        <p>哈哈哈哈哈哈哈p>
        <h1 class="main">Sodah1>
        <p>哈哈哈哈哈哈哈p>
        <p>哈哈哈哈哈哈哈p>
        <p>哈哈哈哈哈哈哈p>

    body>

html>

1.$(this).index()的理解

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


<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 indexbutton>

<ul>
<li>Milkli>
<li class="hot">Teali>
<li class="hot">Coffeeli>
ul>

body>
html>

点击第一个拥有hot的li返回的index是1

而$(selector).index(element)获得元素相对于选择器的 index 位置。该元素可以通过 DOM 元素或 jQuery 选择器来指定。例如:


<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 indexbutton>

<ul>
<li>Milkli>
<li class="hot">Teali>
<li class="hot">Coffeeli>
ul>

body>
html>

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

你可能感兴趣的:(web前端学习)