您的位置:首页 > Web前端 > JQuery

关于jQuery中index()容易错用的地方。

2015-05-31 00:21 603 查看
先上代码

css:
<style>
*{
	margin:0 0 0 0;
	padding:0 0 0 0;
	}
	
div{
	width:400px;
	height:90px;
	border:1px #006699 solid;
	margin-top:10px;
	margin-bottom:10px;
	margin-left:10px;
	}

div div{
	width:100px;
	height:20px;
	border:1px #006699 solid;
	margin-top:10px;
	margin-bottom:10px;
	margin-left:10px;
}
</style>


HTML:

<body>
   <span id="one">div0</span>
   <div id="two" >div1</div>
   <div id="three" class="ooo">div2</div>
   
   <div id="four" class="ooo">
   	div3
   	<div id="five" class="ooo">div4</div>
        <p id="six" class="ooo">p0</p>
        <p id="seven" class="ooo">p1</p>
   </div>
   
   <div id="ppp" class="ooo">
   <span style="white-space:pre">	</span>div5
   	<p id="seven" class="ooo">p2</p>
   </div>

</body>


jQuery

$(document).ready(function(e) {
alert($(".ooo").index($("#six")));//返回id为six的元素在类ooo集合中的索引位置
alert($(".ooo").index($("div")));//返回div对象(jQuery对象)中的第一个元素,在类ooo集合中的索引位置
alert($(".ooo").index('div'));//返回含有类ooo的div在所有div中的索引位置,如果含有ooo的div有多个,那么只返回第一个;若无,则-1
alert($("#three").index());


正文:

且不管id的用法是否合理。

容易错的地方在于第二个alert。

index(),括号里面可以填写无参数, DOM对象,jQuery对象,jQuery对象组;

如果是无参数,那么返回这个参数在同辈中的索引位置。注意!是同辈,不是同类,不是同标签,要在同一个父元素下。

如果是DOM对象,jQuery对象,那么就返回这个对象在 $(".ooo") 中的索引位置,这个很好理解。

如果是jQuery对象组,那么,它返回的是 该对象组的第一个元素 在$(".ooo")中的索引位置

可以id=”three“的div的 class=”ooo“ 剪切到id=”two“的div里面,这样第二个alert输出值为:0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: