jQuery将类添加到div,同时将其从其他对象中删除 [英] jQuery add class to div while removing it from others

查看:48
本文介绍了jQuery将类添加到div,同时将其从其他对象中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试使用DIV构建导航,该导航使用jQuery AJAX函数加载页面.

Hello I am trying to make a navigation constructed from DIV's which uses jQuery AJAX function to load pages.

我想要的事情是,当用户单击页面上的然后是仪表板"或他们所使用的活动页面上的内容时,将称为活动"的类删除并添加到新单击的页面中

The thing I want to is is when user clicks say on Pages then Dashboard or what ever active page they are on has class called active removed and added to the new clicked one

<div class="dijit active" id="dijit_dashboard">Dashboard</div> 
<div class="dijit" id="dijit_pages">Pages</div>

无法完全完成工作的jQuery代码.

jQuery code which doesn't quite do the work.

$("#dijit_pages").click(function() { 
    $("#dijit_utm").load('index.html'); 
    $(this).addClass("active");
});

但是我不确定如何从所有其他活动类中删除活动类.

but I am not sure how to remove class active from all others.

推荐答案

$(function() {
    $(".dijit").live("click", function() {
        $(".dijit").removeClass("active");  // remove active class from all
        $(this).addClass("active");         // add active class to clicked element
        $("#dijit_utm").load('index.html'); 
    });
});

使用此方法将意味着为每个链接加载相同的页面.如果您需要为每个项目加载一个页面,那么以下代码将更合适:

Using this method will mean the same page is loaded for each link. If you need to load a page per item, then the following code will be more apt:

<div class="dijit active" id="dijit_dashboard"><a href="dashboard.html">Dashboard</a></div> 
<div class="dijit" id="dijit_pages"><a href="pages.html">Pages</a></div>

$(function() {
    $(".dijit").live("click", function(e) {
        e.preventDefault();
        $(".dijit").removeClass("active");  // remove active class from all
        $(this).addClass("active");         // add active class to clicked element
        var href = $(this).find("A").attr("href");
        $("#dijit_utm").load(href);
    });
});


更新

这个旧答案似乎仍然获得了相当稳定的观点,因此这是使用最新jQuery方法的更新答案,因为自版本1.7起,已经不推荐使用 live():

This old answer still seems to get quite steady views, so here's an updated answer using the latest jQuery methods as live() has been deprecated since version 1.7:

$(document).on('click', '.dijit', function(e) {
    e.preventDefault();
    var $el = $(this);
    $el.addClass("active").siblings().removeClass('active');
    $("#dijit_utm").load($el.find('a').attr('href'));
});

这篇关于jQuery将类添加到div,同时将其从其他对象中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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