Jquery 带选择器字符串的索引函数

Jquery Index function with selector string

学习Jquery得知,可以使用jquery的函数索引:

我正在测试参数为选择器字符串的索引函数。

html -> 正文:

<div class="name" id="id1">
  <h2>Z</h2>
  <h2>X</h2>
</div>
<div class="name" id="id2">
  <h2>A</h2>
  <h2>B</h2>
</div>

Jquery 脚本:

var index1 = $('.name').index("#id1");
var index2 = $('.name').index("#id2");
alert(index1);
alert(index2);

结果是:index1 为 0(正确),index2 为 -1(不正确)。

所以,问题是:为什么我无法获取到正确的div#id2索引值?

jsfiddle: http://jsfiddle.net/GhPxD/60/

您可以在 index 方法中传递 jquery 对象以使其工作:

var index = $('.name').index($("#id2"));

Working Demo

这里没有错误,API 只是……奇怪。 Here's the documentation :

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

If a selector string is passed as an argument, .index() returns an integer indicating the position of the first element within the jQuery object relative to the elements matched by the selector. If the element is not found, .index() will return -1.

如你所愿

$('#id2').index(".name");

让这个函数以如此不同的方式运行在我看来是非常混乱的。

statement 1 :  var index1 = $('.name').index("#id1");
statement 2 :  var index2 = $('.name').index("#id2");

语句 1 1.As 你知道当你在 jquery 中使用任何选择器时它 return 第一个匹配元素 2. 现在您尝试查找 index("#id1") 的索引,因此它在索引 0 处成功找到,因此它 return 0

语句 2 1.As 你知道当你在 jquery 中使用任何选择器时它 return 第一个匹配元素 2. 现在您尝试查找 index("#id2") 的索引,因此它无法找到具有 #id2 的任何子元素,因此它 reurn -1