页面加载后,在li remove上添加类

add class on li remove after page load

本文关键字:remove 添加 li 加载      更新时间:2023-09-26

我正在使用jquery将类添加到"li"上的活动css中,并导航到一个html页面。但在页面导航后,类在"li"中消失。我尝试了不同的方法来解决这个问题,但都没有抓住要点。

$(document).ready(function(){
    $( '#topList ul li' ).click(function() {
        alert($(this).attr('id'));

        if($(this).attr('id') == "add") {            
            document.location.href = 'localhost:8080/add';
            $(this).attr('id').addClass("active");            
        }
    });    
});

这是菜单列表,我想要的是当我点击li时,它应该调用一个页面添加,并在该li上添加一个类。

html代码

<ul class="nav">
    <li class="" id="add"><a href="javascript:void(0);"  ><i class="add"></i> Add</a>      </li>
<ul>

您需要为正在调用的页面中的li添加类,即,当您调用localhost:8080/add时,页面将被呈现。因为在您的代码设置中,不会调用活动类,因为localhost:8080/add将在前一行代码(document.location.href = 'localhost:8080/add';) 中开始加载

如果要呈现的页面是静态页面,则在该页面中添加此代码。

$(document).ready(function(){
 $('#add').addClass("active"); 
});

在有菜单或链接的页面上使用以下脚本。

<div id="cssmenu">
<a href="blah blah" > Test page</a>
<a href="blah blah" > Test page</a>
</div>


   $(document).ready(function () {
                var pageTitle = window.location.pathname.replace(/^.*'/([^/]*)/, "$1");
                $('#cssmenu a').each(function () {
                    if ($(this).attr('href').toLowerCase() == pageTitle.toLocaleLowerCase())
                        $(this).addClass('active');
                });

            });

我在网站上通过查看URL并决定最好添加哪些导航元素来解决这个问题。

function showContent(target) {
    var e = $('#'+target);
    $(".content").hide();
    $("#nav li.active").removeClass("active");
    $("#nav li[target='"+target+"']").addClass("active");
    e.toggle();
    ga('send','pageview',window.location.pathname+"#"+target);
}
// this looks at the URL (by the #...) and decides which view is active
// this gets called on ready and if the client hits the link 
//   (which dynamically loads instead of making a trip for a new page to the server)
$(window).hashchange(function() {
    var which=window.location.hash.substring(1);
    switch( which) {
    default:
        which="profile";
    case "profile":
    case "resume":
    case "projects":
    case "contact":
        showContent( which);
    }
});
相关文章: