jQuery保持活动菜单项高亮显示
jQuery keep active menu item highlighted
我有一个菜单:http://jsfiddle.net/hu5x3hL1/3/
HTML
<ul id="menu" class="sidebar">
<li> <a href="#" class="clickme">Menu</a>
<ul id="menu1">
<li><a class="dropdown-class-name" href="#">Dropdown link1</a></li>
<li><a class="dropdown-class-name" href="#">Dropdown link2</a></li>
</ul>
</li>
jQuery
$('#menu1 li a').click(function(e) {
$('a').removeClass('dropdown-class-name active');
$(this).addClass('dropdown-class-name active');
});
CSS
#menu1 li a.active{
font-weight:bold;
}
活动菜单项以粗体突出显示。但在我的网站上,当我点击某个下拉链接时,新页面就会打开,但活动菜单项已经不粗体了。如何在网站的新页面上以粗体突出显示?
我试过这样做:
$("#menu1 li a").click(function () {
var url = window.location.href;
if (url == (this.href)) {
$('a').removeClass('dropdown-class-name active');
$(this).addClass('dropdown-class-name active');
}
});
但this.href
返回undefined
,实际上,如果我使用某个链接而不是this.href
,则此代码也不正确。
您必须在dom就绪处理程序中进行检查,而不是在点击处理程序中
$('#menu1 li a').click(function (e) {
$('a').removeClass('dropdown-class-name active');
$(this).addClass('dropdown-class-name active');
});
var url = window.location.pathname;//need to make sure that this is the href value
$('#menu1 li a[href="'+url+'"]').addClass('dropdown-class-name active');
试试这个
$('#menu1 li a').click(function(e) {
if($('a').hasClass('dropdown-class-name active')=="false"){$('a').removeClass('dropdown-class-name active');}
$(this).addClass('dropdown-class-name active');
});
http://jsfiddle.net/hu5x3hL1/4/
下面的代码应该可以使用
$("#menu1 li a").click(function() {
var $Link = $(this); // cache it as we will use ot mote than once
//also url == a.href cannot return true if you use relative url in the link.
//url most likely http://domain.com/pagename href will be just a page name
//if active do nothing
if (!$Link.hasClass("active")) {
$Link.closest("ul") //find menu container
.find("a.active").removeClass('active'); //find active and remove it
$Link.addClass('active');
}
});
您是否尝试将锚点引用放在选择器中?
var localURL = '[href="'+window.location.href+'"]'
$('#menu1 li a'+localURL).click(function(e) {
$('a').removeClass('dropdown-class-name active');
$(this).addClass('dropdown-class-name active');
});
http://jsfiddle.net/hnxhcbgw/1/
请记住,这只会在点击事件时运行,您也应该在加载事件时运行。
相关文章:
- 从桌面读取python文件时高亮显示代码
- 高亮显示时编辑文本大小和颜色
- 高亮显示与数组字符串一起使用时文本插件中断
- FF视图源|脚本高亮显示为红色
- 父页面的角度路由器导航高亮显示
- OpenLayers在悬停时高亮显示功能,并在单击时选择
- 当DIV中的文本高亮显示时,如何获得DIV中Span的值?(Javascript)
- 延迟高亮显示文本区域中的文本
- Mootools:如何在点击时保持元素高亮显示并停止所有事件
- 高亮显示单击菜单链接
- Firefox-当不在输入控件上时隐藏焦点高亮显示
- 高亮显示包含<br>以及重新格式化网格
- 使用下拉选择菜单高亮显示一行表格单元格
- 如何限制javascript高亮显示函数的使用次数
- 在GXT中激活上下文菜单时,如何保持选中的文本高亮显示?(EXT GWT 2.x)
- html5中的文本高亮显示
- Markdown语法高亮显示未按预期工作
- D3js连续一个接一个地高亮显示条
- Javascript:搜索和高亮显示包括HTML标记
- 单击并用CTRL+C复制值时高亮显示html表格单元格