簡體   English   中英

jQuery獲取匹配元素類型之間的索引

[英]jQuery get index among matched element type

是否有比我現有的方法更好的按類型檢測元素索引的方法? <span><em>隔開。 各種各樣的修改向我暗示我仍然是一個無知的程序員。

target.parent('td').children('span').index(target)

HTML看起來像這樣。 我想獲取“時間”的索引3,上面的方法確實如此。 target.index('span')返回27,所以我不知道。

<td>
    <span>once</span>
    <em> </em>
    <span>upon</span>
    <em> </em>
    <span>a</span>
    <em> </em>
    <span>time</span>
    <em> </em>
    <span>in</span>
    <em> </em>
    <span>Mexico</span>
    <em> </em>
</td>

編輯 :我先前的回答是錯誤的,因為我誤解了文檔(即使我認為我認為它的工作方式會更加合乎邏輯),對此感到抱歉!

更新的答案

target.siblings('span').addBack().index(target)應該稍微提高一點效率,因為它不會來回遍歷DOM。

它采用兄弟姐妹跨度+自身,並返回其在其中的位置。

演示:

 $(function() { var target = $('#time'); var position = target.siblings('span').addBack().index(target); console.log(position); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <td> <span>before span 1</span> <span>before span 2</span> <span>before span 3</span> <span>before span 4</span> </td> <td> <span>once</span> <em> </em> <span>upon</span> <em> </em> <span>a</span> <em> </em> <span id="time">time</span> <em> </em> <span>in</span> <em> </em> <span>Mexico</span> <em> </em> </td> </table> 

上一個(錯誤的)答案

只是target.index('span')docs )應該這樣做,除非我誤解了。

演示:

 $(function() { console.log($('#span1').index('span')); console.log($('#span2').index('span')); console.log($('#span3').index('span')); console.log($('#span4').index('span')); console.log($('#span5').index('span')); console.log($('#span6').index('span')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <td> <span id="span1">once</span> <em> </em> <span id="span2">upon</span> <em> </em> <span id="span3">a</span> <em> </em> <span id="span4">time</span> <em> </em> <span id="span5">in</span> <em> </em> <span id="span6">Mexico</span> <em> </em> </td> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM