index

« Обратно на страницу Ядро jQuery


index( объект )

Производит поиск среди выбранных элементов и возвращает индекс элемента, если находит его.  Отсчет начинается с нуля. Если передан объект jQuery, то будет выбран только первый элемент.

Возвращает -1 если объект не был найден.

Аргументы:

объект Элемент,jQuery

Объект для поиска.

Примеры:

По нажатию ЛКМ возвращает индекс соответствующего элемента div на странице.

    $("div").click(function () {
      // this is the dom element clicked
      var index = $("div").index(this);
      $("span").text("That was div index #" + index);
    });
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>

  <script>
  $(document).ready(function(){

    $("div").click(function () {
      // this is the dom element clicked
      var index = $("div").index(this);
      $("span").text("That was div index #" + index);
    });

  });
  </script>

  <style>
  div { background:yellow; margin:5px; }
  span { color:red; }
  </style>
</head>
<body>
  <span>Click a div!</span>
  <div>First div</div>

  <div>Second div</div>
  <div>Third div</div>
</body>
</html>
Возвращает индекс элемента с ID «foobar».

$("*").index( $('#foobar')[0] )
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>

  <script>
  $(document).ready(function(){
    $("*").index( $('#foobar')[0] )
  });
  </script>

</head>
<body>
  <div id="foobar"><b></b><span id="foo"></span></div>
</body>

</html>
Возвращает индекс элемента с ID «foo» в пределах другого элемента.

$("*").index( $('#foo') )
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>

  <script>
  $(document).ready(function(){
    $("*").index( $('#foo') )
  });
  </script>

</head>
<body>
  <div id="foobar"><b></b><span id="foo"></span></div>

</body>
</html>
Возвращает индекс элемента в коллекции, на котором кликнул пользователь.

var mainNavLinks = $('ul#mainNav li a');
mainNavLinks.click(function(){alert(mainNavLinks.index(this));});
Возвращает -1, поскольку элемент с ID «bar» не найден.

$("*").index( $('#bar')[0] )
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>

  <script>

  $(document).ready(function(){
    $("*").index( $('#bar')[0] )
  });
  </script>

</head>
<body>
  <div id="foobar"><b></b><span id="foo"></span></div>

</body>
</html>
Name Type