jquery index()方法

來源:互聯網
上載者:User

標籤:des   style   http   color   io   ar   strong   資料   sp   

搜尋匹配的元素,並返回相應元素的索引值,從0開始計數。

如果不給 .index() 方法傳遞參數,那麼返回值就是這個jQuery對象集合中第一個元素相對於其同輩元素的位置。
        如果參數是一組DOM元素或者jQuery對象,那麼傳回值就是傳遞的元素相對於原先集合的位置。
        如果參數是一個選取器,那麼傳回值就是原先元素相對於選取器匹配元素中的位置。如果找不到匹配的元素,則返回-1。 具體請參考樣本。

<ul>  <li id="foo">foo</li>  <li id="bar">bar</li>  <li id="baz">baz</li></ul>
jQuery 代碼:
$(‘li‘).index(document.getElementById(‘bar‘)); //1,傳遞一個DOM對象,返回這個對象在原先集合中的索引位置$(‘li‘).index($(‘#bar‘)); //1,傳遞一個jQuery對象$(‘li‘).index($(‘li:gt(0)‘)); //1,傳遞一組jQuery對象,返回這個對象中第一個元素在原先集合中的索引位置$(‘#bar‘).index(‘li‘); //1,傳遞一個選取器,返回#bar在所有li中的做引位置$(‘#bar‘).index(); //1,不傳遞參數,返回這個元素在同輩中的索引位置。  

 

 

html:<dl class="topNavDl">    <dt><a href="#" class="selectedNav">資訊查詢</a></dt>    <dd></dd>    <dt><a href="#" id="yewu">業務應用</a></dt>    <dd></dd>    <dt><a href="#">資料維護</a></dt>    <dd></dd>    <dt><a href="#" id="pingtai" >平台服務</a></dt>    <dd></dd>    <dt><a href="#">運行管理</a></dt></dl>  jQuery:$(".topNavDl dt a").click(function(){    alert($(".topNavDl dt a").index(this));});

 

jquery怎麼判斷所點擊元素是其父元素中的第幾個子項目?

比如有如下代碼

HTML code

<div>
<span>內容</span>
<span>內容</span>
<span>內容</span>
<span>內容</span>
</div>

我現在想給span綁定個click事件 $("span").click(function(){})
希望一點擊某個span 顯示出 該span屬於其父元素<div>中的第幾個子項目
應該怎麼寫?

 
$("span").click(function(){
alert($(this).index()+1);
});
index()返回該元素的索引值,可表示該span屬於其父元素<div>中的第幾個子項目。

官網:http://api.jquery.com/index/

jquery index()方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.