jQuery API 返回首页目录 | jQuery API 中英文对照版
index(subject)
index(subject)

搜索与参数表示的对象匹配的元素,并返回相应元素的索引值。

如果找到了匹配的元素,从0开始返回;如果没有找到匹配的元素,返回-1。

返回值:Number

参数

  • subject (Element): 要搜索的对象
 
示例:

返回ID值为foobar的元素的索引值。

HTML 代码:

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

jQuery 代码:

$("").index( $('#foobar')[0] )

结果:

0

示例:

返回ID值为foo的元素的索引值。

HTML 代码:

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

jQuery 代码:

$("").index( $('#foo'))

结果:

2

示例:

因为没有ID值为bar的元素,所以返回 -1。

HTML 代码:

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

jQuery 代码:

$("*").index( $('#bar'))

结果:

-1

 
index( subject )

Searches every matched element for the object and returns the index of the element, if found, starting with zero. Returns -1 if the object wasn't found.

Return value: Number
Parameters:

  • subject (Element): Object to search for
 

Example:

Returns the index for the element with ID foobar

 $("*").index( $('#foobar')[0] )  
Before:
 <div id="foobar"><b></b><span id="foo"></span></div>  
Result:
 0  

Example:

Returns the index for the element with ID foo within another element

 $("*").index( $('#foo')[0] )  
Before:
 <div id="foobar"><b></b><span id="foo"></span></div>  
Result:
 2  

Example:

Returns -1, as there is no element with ID bar

 $("*").index( $('#bar')[0] )  
Before:
 <div id="foobar"><b></b><span id="foo"></span></div>  
Result:
 -1  
相关链接
asp之家 | jQuery官方网站 | jQuery中文网 | 电子书作者网站 | 电子书作者blog