美好的一天。
我有代码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
。
请告诉我怎么做?
答案 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函数!
您可以使用.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/
答案 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");
});