如何在此元素之后和之前更改所有元素的类?

时间:2013-06-12 07:44:55

标签: jquery

美好的一天。

我有代码html:

<span class="empty-star level" style="cursor:pointer" id="1"></span>
<span class="empty-star level" style="cursor:pointer" id="2"></span>
<span class="empty-star level" style="cursor:pointer" id="3"></span>
<span class="empty-star level" style="cursor:pointer" id="4"></span>
<span class="empty-star level" style="cursor:pointer" id="5"></span>

我希望当我点击带有level类的元素之前的所有元素时,将empty-class的类更改为good-class,然后将所有元素更改为{{1}的类} good-class

请告诉我怎么做?

5 个答案:

答案 0 :(得分:4)

您可以将.prevAll()nextAll()用于此目的:

$('.level').on('click', function() {
    $(this)
      .prevAll('.empty-class')
        .toggleClass('empty-class good-class') // remove empty, add good
        .end()
      .nextAll('.good-class')
        .toggleClass('good-class empty-class'); // remove good, add empty
});

答案 1 :(得分:2)

$('.level').on('click', function() {
    $(this).prevAll('.empty-class').removeClass('empty-class').
        addClass('good-class');
    $(this).nextAll('.good-class').removeClass('good-class').
        addClass('empty-class');
});

答案 2 :(得分:0)

您可以使用.prev().next() jQuery函数!

http://api.jquery.com/prev/

http://api.jquery.com/next/

您可以使用.addClass().removeClass()

http://api.jquery.com/addClass/

http://api.jquery.com/removeClass/

//编辑:

如果您想将类分配给多个上一个或下一个元素,可以使用.prevAll() / .nextAll().prevUntil() / .nextUntil()

http://api.jquery.com/prevAll/

http://api.jquery.com/nextAll/

http://api.jquery.com/prevUntil/

http://api.jquery.com/nextUntil/

答案 3 :(得分:0)

你可以试试这个:

$(".level").click(function() {
    var thisId = $(this).attr("id");
    $.each($(".level"), function(index) {
        if(this.id < thisId) {
            $(this).removeClass("empty-class");
            $(this).addClass("good-class");
        }
        else if(this.id > thisId) {
            $(this).removeClass("good-class");
            $(this).addClass("empty-class");
        }
    });
});

答案 4 :(得分:0)

$(".level").click(function()
{
    $(this).prevAll().removeClass("empty-class").addClass("good-class");
    $(this).nextAll().removeClass("good-class").addClass("empty-class");
});