javascript - jQuery - 将事件类添加到菜单中的子菜单

标签 javascript php jquery html css

我有一个侧边栏菜单,我用它来导航整个网站,我希望能够动态地将事件类添加到适当的菜单项。我试过使用下面的代码,但它似乎没有做任何事情。

    var page = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
    $('ul li a[href="'+ page +'"]').parent().addClass('active');
    $('ul li a').filter(function() {
        return this.href == page;
    }).parent().addClass('active');

我的选择器语法可能有误,所以下面我包含了一个侧边栏的片段。

    <div id="sidebar" class="nav-collapse ">
        <ul class="sidebar-menu" id="nav-accordion">
            <li>
                <a href="dash.php">
                    <i class="fa fa-dashboard"></i>
                    <span>Home</span>
                </a>
            </li>

            <li class="sub-menu">
                <a href="javascript:;" >
                    <i class="fa fa-cogs"></i>
                    <span>Tools</span>
                </a>
                <ul class="sub">
                    <li><a href="index.php">Uptime</a></li>
                </ul>
            </li>
        </ul>
    </div>

最佳答案

我建议最简单的方法是过滤 <a> 的集合看哪个元素href属性等于当前页面,然后将“事件”类名添加到最近的祖先 <li>元素:

// caching the URL of the page:
var pageURL = document.location.href;

// selecting all <a> elements within the element with the
// id of 'nav-accordion'; then using the filter() method
// to filter the collection returned by the selector:
$('#nav-accordion a').filter(function (index, anchorEl) {

    // only those elements for which this assessment returns
    // Boolean true will be retained.
    // here we test that the 'href' property (not the attribute),
    // which is an absolute URL, is equal the current page's URL:
    return anchorEl.href === pageURL;

// for those elements remaining in the collection we navigate to
// each retained element's closest ancestor '<li>' element and
// and then add the 'active' class-name to that <li>:
}).closest('li').addClass('active');

引用资料:

关于javascript - jQuery - 将事件类添加到菜单中的子菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32239130/

相关文章:

php - 使用准备好的语句执行类似于 "mysqli_fetch_array"的操作。 PHP MYSQL

jquery - 标题属性值由小写变为大写

javascript - 如果我在密码字段中添加 # 作为模式,如何禁用提交按钮

php - 将 php 变量发布到新窗口

javascript - 淡化背景颜色变化动画滞后并减慢

php - 为什么 php 中的以下 sql 查询不起作用?

jquery - Ajax场景下如何返回错误

javascript - Chart Init 无法正常工作

javascript - Babeljs 为正则表达式 {m,n} 量词产生意外错误

javascript - CSS:点击多个元素