質問

This question might have come up before but I have been searching for hours and have not found a solution that works. I am indexing the buttons of some accordions which is working fine, but there are several parent divs which each have accordions in them, and I need each parent to number their child divs from 1. At the moment the first parent has 1, 2, 3, and the next parent continues at 4, 5, instead of starting again at 1, 2. I hope this makes sense the code is attached, thanks in advance for any help!

    <div class="parent">
        <div class="button"><span>1</span></div>
        <div class="content"></div>
        <div class="button"><span>2</span></div>
        <div class="content"></div>
        <div class="button"><span>3</span></div>
        <div class="content"></div>
    </div>

    <div class="parent">
        <!-- These should start again at 1 -->
        <div class="button"><span>4</span></div>
        <div class="content"></div>
        <div class="button"><span>5</span></div>
        <div class="content"></div>
    </div>


$('.button').each(function(){
            var num = $('.parent .button').index(this) + 1; 
            $(this).append($("<span>" + num + "</span>").addClass("number"));       
        });
役に立ちましたか?

解決

$('.button').append(function() {
    return $('<span />', {text: $('.button', this.parentNode).index( this ) + 1})
});

FIDDLE

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top