简体   繁体   English

jQuery在重新加载时将活动类添加到父类

[英]JQuery add active class to parent class on reload

My "active" class does not work when i replace "#" from href to an URL. 当我将href中的“#”替换为URL时,“活动”类不起作用。 When i click on the link, the page refresh and the "active" class does not change. 当我单击链接时,页面刷新,并且“活动”类未更改。 This is the working code before i change # to URL. 这是我将#更改为URL之前的工作代码。

<ul class="additional-menu">
<li class="active"><a href="#">Link1</a></li>
<li><a href="#" id="link2">Link2</a>
<ul>
<li><a href="#" id="link2.1">Link2.1</a></li>
</ul>
</li>
<li><a href="#" id="link3">Link3</a></li>

Jquery: jQuery的:

$('.additional-menu a').on('click', function() {
var t = $(this);
t.parents('.additional-menu').find('li').removeClass('active'); 
t.parentsUntil('.additional-menu', 'li').addClass('active'); 

}) })

after changing(not working): 更改后(不起作用):

 <ul class="additional-menu">
 <li class="active"><a href="link1.php">Link1</a></li>
 <li><a href="link1.php" id="link2">Link2</a>
 <ul>
 <li><a href="link2-1.php" id="link2.1">Link2.1</a></li>
 </ul>
 </li>
 <li><a href="link3.php" id="link3">Link3</a></li>
 </ul>

When you click on a URL link, the page is being refreshed and the current Jquery wont work anymore. 当您单击URL链接时,页面正在刷新,当前的Jquery将不再起作用。 You have to update your codes to determine the active menu according to the page URL on page load or on DOM ready not onClick . 您必须根据页面加载时或不准备使用 onDOM的 DOM 的页面URL更新代码来确定活动菜单。

The you have to set the active class to the menu which has the found filename as href attribute. 您必须将活动类设置为具有找到的文件名作为href属性的菜单。

Here is full code using jquery selectors: 这是使用jquery选择器的完整代码:

 $(document).ready(function(){
    var fullpath =window.location.pathname;
    var filename=fullpath.replace(/^.*[\\\/]/, '');
    //alert(filename);
    var currentLink=$('a[href="' + filename + '"]'); //Selects the proper a tag
    currentLink.parent().addClass("active");
    }))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM