如何获取选择数组中元素的索引?

时间:2019-05-15 09:58:56

标签: javascript jquery dom frontend

我需要获取与其父母其他相关的多个元素的索引。 在下面的代码中,我认为它应该为我提供与同一<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

2 个答案:

答案 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>

答案 1 :(得分:0)

因为您使用了相同的类名,所以以下示例更改了第二个<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')));
    });