gpt4 book ai didi

javascript - 如何根据位置和相应的href添加类?

转载 作者:行者123 更新时间:2023-12-02 17:01:41 26 4
gpt4 key购买 nike

我有一个带有简单标记的菜单,我的目标是向菜单添加一个类 <li>项目自动按当前页面的名称...

相关标记是:

    <ul class="sub-menu">
<li >
<a href="page_example_one.html">

<i class="icon-time"></i>

Timeline</a>
</li>
<li >
<a href="page_example_two.html">

<i class="icon-cogs"></i>

Page Two</a>
</li>
.... Many other elements
</ul>

当我在某个页面上时,我需要得到的非常简单(假设 page_example_one.html)我需要相应的<li>元素有一个像这样的附加类

<li class="active">

<a href="page_example_one.html">

<i class="icon-time"></i>

Timeline</a>

</li>

我尝试用 jQuery 来做到这一点:

jQuery(document).ready(function() {

// Get the current page name ( pathname)
var currentUrl = jQuery(location).attr('pathname');

// Get the element ( try at least )
var currentMenuItem = jQuery("sub-menu li a[href='" + currentUrl + "']");

// Add the class
currentMenuItem.addClass("active");

//Tried also something like this :
// jQuery("sub-menu li a[href='" + currentUrl + "']").find('a').addClass("active");


});

上述两种方法对我来说都失败了 - (带有 VAR 注释的方法,以及连接的方法)但是因为我的 JS 技能非常低,所以我无法真正看出我做错了什么(对于了解 JS 的人来说可能是非常明显的事情)

解决此问题后,我还想知道如何根据当前页面链接将跨度或类添加到父菜单项(如果是子菜单)...

最佳答案

var currentMenuItem = jQuery("a[href='" + currentUrl + "']").parent()

添加演示 here

关于javascript - 如何根据位置和相应的href添加类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25649643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com