如何在单击引导程序中的另一个链接时更改活动类使用 jquery?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17975922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:17:58  来源:igfitidea点击:

How to change active class while click to another link in bootstrap use jquery?

javascriptjqueryhtmltwitter-bootstrap

提问by Tanky Woo

I have a html as sidebar, and use Bootstrap.

我有一个 html 作为侧边栏,并使用Bootstrap.

<ul class="nav nav-list">
    <li class="active"><a href="/">Link 1</a></li>
    <li><a href="/link2">Link 2</a></li>
    <li><a href="/link3">Link 3</a></li>
</ul>

I want to do some thing:

我想做些事:

When I clicka link such as Link 3, the page contentwill change to Link 3's content, and the Link 3 will have class active, and remove the active clss in Link 1.

当我click创建链接 3 等链接时,page content将更改为链接 3 的内容,链接 3 将具有 class active,并删除链接 1 中的活动类。

I think this can be implemented in jQuery, and I have searched many question in SO, such as:

我认为这可以在 中实现jQuery,并且我在 SO 中搜索了许多问题,例如:

I use this script:

我使用这个脚本:

$(document).ready(function () {
    $('.nav li').click(function(e) {

        $('.nav li').removeClass('active');

        var $this = $(this);
        if (!$this.hasClass('active')) {
            $this.addClass('active');
        }
        //e.preventDefault();
    });
});

But most of them use preventDefault, this will prevent the continued action. So it can't change to Link 3's page content.

但是他们中的大多数使用preventDefault,这将阻止继续操作。所以它不能更改为Link 3 的页面内容。

If I remove the preventDefault statement, when the page load Link 3's content, the active class will back to Link 1.

如果我删除 preventDefault 语句,当页面加载链接 3 的内容时,活动类将返回链接 1。

So Is there any way to solve this problem?

那么有没有办法解决这个问题呢?

回答by Karl-André Gagnon

You are binding you click on the wrong element, you should bind it to the a.

您正在绑定您单击错误的元素,您应该将其绑定到a.

You are prevent default event to occur on the li, but lihave no default behavior, adoes.

您可以防止在 上发生默认事件li,但li没有默认行为a

Try this:

尝试这个:

$(document).ready(function () {
    $('.nav li a').click(function(e) {

        $('.nav li.active').removeClass('active');

        var $parent = $(this).parent();
        $parent.addClass('active');
        e.preventDefault();
    });
});

回答by Fazil Khan

I am using bootstrap navigation

我正在使用引导程序导航

This did the job for me including active main dropdown's and the active children

这为我完成了工作,包括活跃的主下拉菜单和活跃的孩子

$(document).ready(function () {
        var url = window.location;
    // Will only work if string in href matches with location
        $('ul.nav a[href="' + url + '"]').parent().addClass('active');

    // Will also work for relative and absolute hrefs
        $('ul.nav a').filter(function () {
            return this.href == url;
        }).parent().addClass('active').parent().parent().addClass('active');
    });

回答by hsusyh

I had the same issue before. Try this answer here, it works on my site.

我之前也遇到过同样的问题。在这里试试这个答案,它适用于我的网站。

$(function(){
  var current_page_URL = location.href;
  $( "a" ).each(function() {
     if ($(this).attr("href") !== "#") {
       var target_URL = $(this).prop("href");
       if (target_URL == current_page_URL) {
          $('nav a').parents('li, ul').removeClass('active');
          $(this).parent('li').addClass('active');
          return false;
       }
     }
  });
});

Source: It was original posted here how to set active class to nav menu from twitter bootstrap

来源:最初发布在这里如何从 twitter 引导程序将活动类设置为导航菜单

回答by Daniel Apt

If you change the classes andload the content within the same function you should be fine.

如果您更改类在同一函数中加载内容,您应该没问题。

$(document).ready(function(){
    $('.nav li').click(function(event){
        //remove all pre-existing active classes
        $('.active').removeClass('active');

        //add the active class to the link we clicked
        $(this).addClass('active');

        //Load the content
        //e.g.
        //load the page that the link was pointing to
        //$('#content').load($(this).find(a).attr('href'));      

        event.preventDefault();
    });
});

回答by Milan

<script type="text/javascript">
$(document).ready(function(){
    $('.nav li').click(function(){
        $(this).addClass('active');
        $(this).siblings().removeClass('active');

    });

});

回答by Didiencho

$(".nav li").click(function() {
    if ($(".nav li").removeClass("active")) {
        $(this).removeClass("active");
    }
    $(this).addClass("active");
});

This is what I came up with. It checks if the "li" element has the class of active, if it doesn't it skips the remove class part. I'm a bit late to the party, but hope this helps. :)

这就是我想出的。它检查“li”元素是否具有活动类,如果没有,则跳过删除类部分。我参加聚会有点晚了,但希望这会有所帮助。:)

回答by Rajput

You can use cookies for save postback data from one page to another page.After spending a lot time finally i was able to make this happen. I am suggesting my answer to you(this is fully working since I also needed this).

您可以使用 cookie 将回发数据从一个页面保存到另一个页面。花了很多时间之后,我终于能够做到这一点。我向你建议我的答案(这是完全有效的,因为我也需要这个)。

first give your li tag to valid id name like

首先将您的 li 标签赋予有效的 id 名称,例如

<ul class="nav nav-list">
    <li id="tab1" class="active"><a href="/">Link 1</a></li>
    <li id="tab2"><a href="/link2">Link 2</a></li>
    <li id="tab3"><a href="/link3">Link 3</a></li>
</ul>

After that copy and paste this script. since I have written some javascript for reading, deleting and creating cookies.

之后复制并粘贴此脚本。因为我已经编写了一些用于读取、删除和创建 cookie 的 javascript。

 $('.nav li a').click(function (e) {
  
        var $parent = $(this).parent();
        document.cookie = eraseCookie("tab");
        document.cookie = createCookie("tab", $parent.attr('id'),0);
 });

    $().ready(function () {
        var $activeTab = readCookie("tab");
        if (!$activeTab =="") {
        $('#tab1').removeClass('ActiveTab');
          }
       // alert($activeTab.toString());
       
        $('#'+$activeTab).addClass('active');
    });

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";

    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

Note: Make sure you have implmeted according to your requirement. I have written this script according to my implementation and its working fine for me.

注意:请确保您已根据您的要求实现。我已经根据我的实现编写了这个脚本,它对我来说工作正常。

回答by Martin Mbae

This will do the trick

这将解决问题

 $(document).ready(function () {
        var url = window.location;
        var element = $('ul.nav a').filter(function() {
            return this.href == url || url.href.indexOf(this.href) == 0;
        }).addClass('active').parent().parent().addClass('in').parent();
        if (element.is('li')) {
            element.addClass('active');
        }
    });

回答by amarjeet singh

html code in my case

在我的情况下的 html 代码

<ul class="navs">
   <li  id="tab1"><a href="index-2.html">home</a></li>
   <li id="tab2"><a href="about.html">about</a></li>

   <li id="tab3"><a href="project-02.html">Products</a></li>

   <li id="tab4"><a href="contact.html">contact</a></li>
 </ul>

and js code is

和js代码是

  $('.navs li a').click(function (e) {
        var $parent = $(this).parent();
        document.cookie = eraseCookie("tab");
        document.cookie = createCookie("tab", $parent.attr('id'),0);
 });

    $().ready(function () {
        var $activeTab = readCookie("tab");
        if (!$activeTab =="") {
        $('#tab1').removeClass('ActiveTab');
          }
       // alert($activeTab.toString());

        $('#'+$activeTab).addClass('active');
    });

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";

    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

回答by Lok R BHATTA

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$(document).ready(function () {
        var url = window.location;
        $('ul.nav a[href="' + url + '"]').parent().addClass('active');
        $('ul.nav a').filter(function () {
            return this.href == url;
        }).parent().addClass('active').parent().parent().addClass('active');
    });
    
    This works perfectly