[英]active state menu javascript
I'm having trouble to setup the active state for my menu using URL recognition. 我无法使用URL识别来设置菜单的活动状态。 What I'm looking to achieve is having the <a href="">
to change to <a id="active" href ="">
if you're on the page it links to. 我要实现的是让<a href="">
更改为链接到的页面上的<a id="active" href ="">
。 This what I have done so far and it seems not working. 我到目前为止所做的一切,似乎没有用。
Let me know if you have any idea and thanks all for your help! 让我知道您是否有任何想法,感谢大家的帮助!
$(function(){
var url = window.location.href;
var page = url.substr(url.lastIndexOf('/')+1);
$('.ActiveMenu a[href*="'+page+'"]');
$(this).attr({ id: 'active'});});
<ul id="menu">
<li id="Link1" class="ActiveMenu"><a href="URL1">Link 1</a></li>
<li id="Link2" class="ActiveMenu"><a href="URL2">Link 2</a></li>
<li id="Link3" class="ActiveMenu"><a href="URL3">Link 3</a></li>
</ul>
so the issue is that your function doesn't know what $(this) is . 所以问题是您的函数不知道$(this)是什么 。 Instead, you should set target to the correct element and then add a class to it. 相反,您应该将target设置为正确的元素 ,然后向其添加一个类。 You shouldn't use id because you should only have one id and it should be a unique identifier, not a state. 您不应该使用id,因为您应该只有一个id,并且它应该是唯一的标识符,而不是状态。 Class is better suited for it. 类更适合它。 Let me know if this works for you! 让我知道这是否适合您! :) :)
DEMO DEMO
$(function(){
var url = window.location.href;
var page = url.substr(url.lastIndexOf('/')+1);
target = $('.ActiveMenu a[href*="'+page+'"]');
$(target).addClass('active');
});
<ul id="menu">
<li id="Link1" class="ActiveMenu"><a href="URL1">Link 1</a></li>
<li id="Link2" class="ActiveMenu"><a href="URL2">Link 2</a></li>
<li id="Link3" class="ActiveMenu"><a href="URL3">Link 3</a></li>
</ul>
Please add/change the class name instead of Id 请添加/更改班级名称而不是ID
$(function(){
var url = window.location.href;
var page = url.substr(url.lastIndexOf('/')+1);
var currentPage=$('.ActiveMenu a[href*="'+page+'"]');
currentPage.addClass('active');
});
请用
$(this).attr("id","active");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.