我正在开发一个包含约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
发布评论