向下一个元素添加/删除类的最佳方法? [英] The best way to add/remove class to next element?
问题描述
HTML
<div class="item active" data-category="sharks">
<div class="item" data-category="tigers">
<div class="item" data-category="lions">
<a href="#" class="btn btn-primary" id="next-button" rel="nofollow">Next</a>
$("#next-button").click(".item:not(.active)", function (event) {
$(".item.active", event.delegateTarget).removeClass("active");
$(this).next().addClass("active");
});
我正在尝试将active
添加到下一个.item
类,并从上一个.item
类中删除.item
.
I am trying to add active
to the next .item
class and remove .item
from the previous.. easy I know.
还有另一件事,当单击特定的数据ID并将其添加到匹配的数据类别时,如何添加.active
?
also one more thing, how do I add .active
when a specific data-id is clicked adding it to the matching data-category?
基本上,有两种方法可以将Active添加到.item
中,一种是从下一个按钮添加,然后从导航中添加,就像您在小提琴中看到的一样.
Basically two ways to add active to .item
one from the next button, and then also from the navigation like thing you will see in the fiddle
推荐答案
您目前拥有的东西由于各种原因将永远无法使用,其中主要的原因是:
What you currently have will never work for a variety of reasons, chief amongst them:
- 您的
.items
都不是#next-button
的孩子. - 使用
.click
不会委派.在您的示例中,".item:not(.active)"
是要传递给处理程序的数据.
- None of your
.items
are children of#next-button
. - Using
.click
does not delegate. In your example,".item:not(.active)"
is data that is being passed to the handler.
如果您要这样做,则当有人单击#next-button
时,active
类会移动:
If you are trying to make it so when someone clicks the #next-button
the active
class moves:
var items = $('div.item');
var currentItem = items.filter('.active');
$('#next-button').on('click', function() {
var nextItem = currentItem.next();
currentItem.removeClass('active');
if ( nextItem.length ) {
currentItem = nextItem.addClass('active');
} else {
// If you want it to loop around
currentItem = items.first().addClass('active');
}
});
如果要单击项目并进行更改:
If you want to click on the items and change:
var items = $('div.item').on('click', function() {
var target = $(this);
if ( ! target.hasClass('active') ) {
$(this).addClass('active').siblings('.active').removeClass('active');
}
});
这篇关于向下一个元素添加/删除类的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!