将活动类添加到基于URL的导航菜单javascript

编程入门 行业动态 更新时间:2024-10-09 18:16:51
本文介绍了将活动类添加到基于URL的导航菜单javascript-仅在发出警报时有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在开发一个包含约8/10个网页的网站.我已经使用javascript实现了通用的页眉和页脚,效果很好.下一步是将一个活动类添加到导航菜单中,我可以通过javascript或jquery来阅读该菜单.我偶然发现了同时具有jquery和javascript方法的一篇文章. 如何根据URL将活动类添加到导航菜单

I am developing a website containing about 8/10 webpages. I have implemented a common header and footer using javascript which is working fine. The next step was to add a active class to the navigation menu which I read is possible either through javascript or jquery. I stumbled upon a article which had both the jquery as well as the javascript method. How to Add Active Class to a Navigation Menu Based on URL

仅当我添加警报时,jquery方法对我来说似乎才能正常工作 之间的陈述.

The jquery method seems to be working fine for me only when I add an alert statement in between.

$(function() { var pgurl = window.location.href.substr(window.location.href .lastIndexOf("/")+1); alert(pgurl); //Works fine if this statement is included $("#nav ul li a").each(function(){ if($(this).attr("href") == pgurl || $(this).attr("href") == '' ) $(this).addClass("active"); }) });

我确实又引用了几篇文章,并且看起来大多数文章或多或少都使用相同的方法.有什么建议吗?

I did refer a few more articles and looks like most of them use the same method more or less. Any suggestion?

推荐答案

使用一些timeout,可能是您的视图暂时未准备好,请尝试以下代码:-

Use some timeout, may be your view is not ready for sometime, try following code :-

$(function() { setTimeout(function(){ var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1); $("#nav ul li a").each(function(){ if($(this).attr("href") == pgurl || $(this).attr("href") == '' ) $(this).addClass("active"); }); }, 5000); });

这可能会对您有所帮助.

It may help you.

更多推荐

将活动类添加到基于URL的导航菜单javascript

本文发布于:2023-11-27 21:23:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639652.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:菜单   URL   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!