将类活动添加到“li”中如果链接 init 具有相同的使用 Jquery
我有一个像这样的菜单,
<li> <a href="/home" class="active">Home</a> </li>
<li> <a href="/service">Services</a></li>
我希望链接处于活动状态的 li 具有“活动”类。所以它会变成
<li class="active"> <a href="/home" class="active">Home</a> </li>
我认为代码可以是这样的,但还没有完全明白
var $this;
$("ul > li").each(function(){
$this = $(this);
if($this.find("> li a.active").length)
$this.addClass("active");
}
Am having a menu like this
<li> <a href="/home" class="active">Home</a> </li>
<li> <a href="/service">Services</a></li>
I want the li in which the link has active have the class "active". So it will become
<li class="active"> <a href="/home" class="active">Home</a> </li>
I think code can be something like this, but not quite getting it though
var $this;
$("ul > li").each(function(){
$this = $(this);
if($this.find("> li a.active").length)
$this.addClass("active");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不找到类为“活动”的元素并获取其父级并添加类。这可能很简单:
Why don't you find the element whose class is "active" and get its parent and add class. This could be as simple as:
查看 children() 选择器:
来自 docs
对象
Check out the children() selector:
From the docs
Cheers
我不确定你想做什么,但我想这就是你正在寻找的代码
I'm not sure what you are trying to do, but I guess this is the code you are looking for