从单个类中渲染菜单栏,并在Yii2中动态突出显示菜单

时间:2016-09-26 08:51:40

标签: javascript yii2 render

我的Yii2项目中的顶级菜单栏是单独的。我在索引文件中渲染它们并使用它们。

js文件动态使用活动类。

$(document).ready(function () {
    var url = window.location;
    // Will only work if string in href matches with location
    $('ul.navbark a[href="' + url + '"]').parent().addClass('active');
    // Will also work for relative and absolute hrefs
    $('ul.navbark a').filter(function () {
        return this.href == url;
    }).parent().addClass('active').parent().parent().addClass('active');
});

效果很好。它准确地分配活动类,但问题是当我在同一页面中使用搜索时。 URL更改导致问题。当我提交搜索表单时,活动类将被删除。我怎样才能解决这个问题?

谢谢!

1 个答案:

答案 0 :(得分:0)

我找到了问题的解决方案:

到目前为止,我没有使用yii2 Navbar而是使用了html。当我使用yii2 Navbar时,我不必调用任何javascript。

这是我的菜单栏视图页面:views / topmenu / chemicalinventory.php

'Y'

现在我可以在任何视图页面中渲染它。

<?php echo yii\bootstrap\Nav::widget([
    'items' => [
        ['label' => Yii::t('app','Inventory'),'url' => ['/product/index']],
        ['label' => Yii::t('app','Requests'),'url' => ['/product-requests/index']],
        ['label' => Yii::t('app','Deleted'),'url' => ['/productlines-deleted/index']],
    ],
    'options' => ['class' =>'nav nav-tabs nav-tab nav-text navbark'],    
]);
?>

我的顶级菜单的CSS

 <?php echo \Yii::$app->view->renderFile('@app/views/topmenu/chemicalinventory.php'); ?>

这将给出如下图所示的输出:

Click Here