如何分配“活动"类别?基于当前URL的li元素并使用jQuery或JavaScript单击事件 [英] How to assign a class "active" to the li element based on current URL and click event using jQuery or JavaScript
本文介绍了如何分配“活动"类别?基于当前URL的li元素并使用jQuery或JavaScript单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创造一个类活动",只要选中它并加载被分配到该页面的菜单.现在,默认情况下它仅应用于索引页面.
I am trying to create a menu where a class "active" is assigned to the page whenever it's selected and loaded. Right now it is applied only to the index page by default.
我的菜单片段:
<ul class="nav navbar-nav">
<li class="active"><a href="http://localhost/wp/index.php">Main</a></li>
<li><a href="http://localhost/wp/news">News</a></li>
<li><a href="http://localhost/wp/contacts">Contacts</a></li>
</ul>
推荐答案
尝试此代码.它在我的工作结束.
Try this code. Its working at my end.
<script>
jQuery(document).ready(function() {
jQuery(".nav.navbar-nav li").click(function(){
jQuery(".nav.navbar-nav li").removeClass('active');
jQuery(this).addClass('active');
})
var loc = window.location.href;
jQuery(".nav.navbar-nav li").removeClass('active');
jQuery(".nav.navbar-nav li a").each(function() {
if (loc.indexOf(jQuery(this).attr("href")) != -1) {
jQuery(this).closest('li').addClass("active");
}
});
});
</script>
<ul class="nav navbar-nav">
<li class="active"><a href="http://localhost/wp/index.php">Main</a></li>
<li><a href="http://localhost/wp/news">News</a></li>
<li><a href="http://localhost/wp/contacts">Contacts</a></li>
</ul>
这篇关于如何分配“活动"类别?基于当前URL的li元素并使用jQuery或JavaScript单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文