-5

I've got a problem with .index() function in jQuery.

Outline of DOM:

<div class="one">
    <div class="two">
        <div class="three"></div>
        <div class="three"></div>
        <div class="three"></div>
    </div>
    <div class="threeB"></div>
    <div class="threeB"></div>
    <div class="threeB"></div>
</div>

<div class="one">
    <div class="two">
        <div class="three"></div>
        <div class="three"></div>
    </div>
    <div class="threeB"></div>
    <div class="threeB"></div>
</div>

<div class="one">
    <div class="two">
        <div class="three"></div>
        <div class="three"></div>
        <div class="three"></div>
    </div>
    <div class="threeB"></div>
    <div class="threeB"></div>
    <div class="threeB"></div>
</div>

According to which of threes in two a user clicks, one of the threeBs are displayed. I wanted to do this with .index() function, but it fails for all but the first ones. In the second one class, the two threes have indexes 3 and 4 (instead of desired 0 and 1). On the other hand, .eq() for threeBs seems to work as desired.

Any neat way to solve this without having to count how many threes were there before the div in question?

4

1 回答 1

1

它是这样工作的:

$('.three').click(function(){
    $(this).parent().parent().find('.threeB').eq($(this).index())
        .css('background','green');
});

在这里检查:jsFiddle

于 2013-08-02T11:51:25.760 回答