簡體   English   中英

如何獲取選擇數組中元素的索引?

[英]how to get the index of an element in the selection array?

我需要獲取有關其父級 OL的多個元素的索引 在下面的代碼中,我認為它應該給我與注釋和標簽相同的索引,就像它們在同一個<ol>但是不會發生。

 $('#main-form').find('form').each(function () { //foreach form in the ol tag var $drop_target_index = $('.drop_targets').index($(this).closest('.drop_targets')); console.log($(this).closest('.drop_targets')); console.log( $drop_target_index); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="main-form"> <ol class="drop_targets"> <li><ol class="drop_targets comments"> <li><form></form> Item 1 </li> </ol> <ol class="drop_targets tags"> <li><form></form> Item 2</li> </ol></li> </ol> </div> 

我期望0 0我得到0 1

each().drop_targets

 $('.drop_targets .drop_targets').each(function () { var $drop_target_index = $(this).parent().index() + 1; console.log($drop_target_index); }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="main-form"> <ol class="drop_targets"> <ol class="drop_targets comments"> <form></form> <form></form> <form></form> Item 1 </ol> <ol class="drop_targets tags"> <form></form> <form></form> <form></form> Item 2 </ol> </ol> </div> 

因為您使用了相同的類名,所以以下示例更改了第二個<ol>類以獲取索引。

<div id="main-form">
<ol class="drop_targets">
    <ol class="drop_targets1 comments">
        <form></form>
        <form></form>
        <form></form>

        Item 1
    </ol>
    <ol class="drop_targets1 tags">
        <form></form>
        <form></form>
        <form></form>
        Item 2
    </ol>
</ol>

$('#main-form').find('form').each(function (i,e) { 
console.log($('.drop_targets1').index($(e).closest('.drop_targets1')));
});

另一個解決方案不需要編輯類名

    $('#main-form').find('form').each(function (i,e) { 
        console.log($($('.drop_targets')[0]).find('.drop_targets').index($(e).closest('.drop_targets')));
    });

暫無
暫無

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

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