2013-12-16 45 views
0

我正在使用jquery将该类添加到“li”上的活动css,并导航到html页面,但在页面导航“li”上的类disappers之后。我尝试过不同的方法来解决这个问题,但没有明白。在li上添加class在页面加载后删除

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

这里是菜单列表,我想要的是当我点击李应调用页面中添加,也对李加个班。

HTML代码

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

对不起,我编辑了这个问题。 Pleae现在检查 –

+0

你说'悬停'状态,但你正在使用'点击'事件! – DontVoteMeDown

+0

无论如何,我相信你应该使用这个:'$(this).addClass(“active”)'。 – DontVoteMeDown

回答

1

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

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



      }); 
+0

好的。那么如何在同一时间导航一个页面? –

+0

您可以使用与您已经做过的相同的代码进行重定向。这仅用于控制活动页面上的活动类。看到更新的答案。 –

+0

我用你唯一的window.location.pathname.replace代码行,它工作,所以没有使用下面的代码。 :)。谢谢。我在我的if条件中使用了这个代码,并且hrefs已经在html中进行了修改。休息的if将与你的这一行代码window.location.pathname一起工作。再次感谢。 –

1

我通过查看URL,并决定该导航元素是最好的补充解决在my website这个问题。

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

您需要添加类为你调用即页面里,当你调用localhost上的页面将呈现:8080 /加。 因为在代码中设置活动类不会被调用的,因为本地主机:8080 /加将在代码(document.location.href = 'localhost:8080/add';)

前行开始加载如果要呈现的页面是静态页面,然后添加以下代码在该页面中。

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

好的,但是如何解决呢?你能给他一些解释吗? –

+0

我知道这是事实,但如何解决这个问题?调用url并在li上添加一个类。 –

+0

你正在渲染的是一个静态的html页面? –

相关问题