How to use the index of a single <li> to identify the corresponding <li>

Worked on this issue, and I'm upset that I don’t know how to create a pointer and pointer instance through jQuery.

I have two lists:

<div class="listSet">
    <ul id="list1">
        <li>One bug <a href="#">X</a></li>
        <li>Two bug <a href="#">X</a></li>
        <li>Three bug <a href="#">X</a></li>
    </ul>
</div>
</div class="listSet">  
    <ul id="list2">
        <li><img src="bug1.jpg"></li>
        <li><img src="bug2.jpg"></li>
        <li><img src="bug3.jpg"></li>
    </ul>
</div>

I use click capture on the first list to indicate the index of this unordered list:

var theBox = $(this).parents('li');
theBoxInd = $('#list ul li').index(theBox);

How to get the descriptor of the corresponding LI in the second list? I wanted to remove them from the screen, but I cannot reproduce the idea that the index of the second list could .remove()use two LIs.

Any help is appreciated.

+3
source share
2 answers

You can use a combination of the add () and index () method to achieve this:

$("#list1 li a").click(function(e) {
    e.preventDefault();
    var $li = $(this).parent();
    $("#list2 li:eq(" + $li.index() + ")").add($li).remove();
});

li index

: http://jsfiddle.net/cttZn/5/


:nth-child :

$("#list1 li a").click(function() {
    var child = $(this).parent().index() + 1;
    $("#list1, #list2").find("li:nth-child(" + child + ")").remove();
});

: http://jsfiddle.net/cttZn/8/

+4

:

$('#list1 > li > a').click(function(e) {
    e.preventDefault();
    var idx = $(this).closest('li').index();
    var corresp = $('#list2 > li').eq(idx);
    alert(corresp.children('img').attr('src'));
    // to remove the <li> element: corresp.remove();
});

http://jsfiddle.net/ThiefMaster/yM3aD/

+1

Source: https://habr.com/ru/post/1788587/


All Articles