向下一个元素添加/删除类的最佳方法? [英] The best way to add/remove class to next element?

查看:76
本文介绍了向下一个元素添加/删除类的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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");
});

FIDDLE

我正在尝试将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:

  1. 您的.items都不是#next-button的孩子.
  2. 使用.click不会委派.在您的示例中,".item:not(.active)"是要传递给处理程序的数据.
  1. None of your .items are children of #next-button.
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆