重定向到另一个页面时,如何保持"活动"类对li标签?



我有2个菜单管理类别并管理产品,单击时它会变成'活动'。问题是,当我去添加产品页面菜单"管理产品"不要保持"活动")时,有"添加产品"按钮"添加产品"。

<aside class="main-sidebar">
    <section class="sidebar">
        <ul class="sidebar-menu">
            <li>
                <a href="manage_category.php">
                <i class="fa fa-table"></i> <span>Manage category</span>
                </a>
            </li>
                <li>
                <a href="manage_products.php">
                <i class="fa fa-table"></i> <span>Manage products</span>
                </a>
            </li>
        </ul>
    </section>
    <!-- /.sidebar -->
</aside>
<script type="text/javascript">
$(document).ready(function() {
    var url = window.location;
    // for sidebar menu entirely but not cover treeview
    $('ul.sidebar-menu a').filter(function() {
        return this.href == url;
    }).parent().addClass('active');
});
</script>

您可以在菜单中添加隐藏的链接

中的'添加产品'
<li>
 <a href="manage_products.php">
  <i class="fa fa-table"></i> <span>Manage products</span>
 </a>
 <a href="add_product.php" style="display:none"></a>
</li>

,您的JavaScript代码应为

起作用

您的窗口。Location不仅返回整个网址。

这在工作:

$(document).ready(function() {
    var url = location.pathname.split('/').slice(-1)[0];
    jQuery('ul.sidebar-menu a').each(function() {
        if($(this).attr('href') == url)
            $(this).parent().addClass('active');
    });
});

我怀疑您的过滤器中的url(window.location)!= this.href。

this.href将是例如Manage_products.php但是window.location是一个对象。(检查MDN文档中的Window.Location)。https://developer.mozilla.org/en-us/docs/web/api/location

均匀的window.location.href仍然会给您完整的URL。但 - window.location.pathname可能接近您想要的。

如果您在此行上调试代码:返回this.href == url;并检查您会看到您的问题的值。

如果"添加产品"不是不同的页面,请尝试以下代码。

var parameter = Sys.WebForms.PageRequestManager.getInstance();
parameter.add_endRequest(function () {
var url = window.location;
    // for sidebar menu entirely but not cover treeview
    $('ul.sidebar-menu a').filter(function() {
    return this.href == url;
    }).parent().addClass('active');
})

最新更新