简体   繁体   English

jQuery自动选择菜单项。

[英]Jquery Auto select Menu Item.

Hi i am trying to select navigation item once user click on them and they should remain selected once page load up. 嗨,我试图在用户单击导航项目后选择它们,并且在页面加载后它们应该保持选中状态。 I have tried many examples and none is working for me. 我尝试了许多示例,但没有一个对我有用。

Here is what i have in header. 这是我标题中的内容。

<nav id="navigation">

<ul id = "nav-ul">
        <li><a href="<?php echo $this->base?>/Logins/index">item1</a></li>
        <li> <a href="<?php echo $this->base?>/Logins/item2">item2</a></li>
        <li><a href="<?php echo $this->base?>/Logins/item3">item3</a></li>

</ul>

    </nav>

And here is what i have in script.js. 这就是我在script.js中拥有的东西。 Script is added in all files. 脚本已添加到所有文件中。

last one i tried 我尝试的最后一个

$(document).ready(function(){


    $('#navigation ul li a').each(function(index) {
        if(this.href.trim() == window.location)
            $(this).addClass("selected");
    });
});

Than tried this 比尝试这个

$(document).ready(function(){

    var pgurl = window.location.href.substr(window.location.href
        .lastIndexOf("/")+1);
    $("#navigation ul li a").each(function(){
        if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
            $(this).addClass("active");
        $("#navigation ul li a").selected
    })
});

Nothing seems to work. 似乎没有任何作用。

this is ypur mark up 这是ypur标记

<ul id = "nav-ul">
    <li><a href="<?php echo $this->base?>/Logins/index"    >item1</a></li>
    <li> <a href="<?php echo $this->base?>/Logins/item2"      >item2</a></li>
    <li><a href="<?php echo $this->base?>/Logins/item3"      >item3</a></li>

then 然后
get the file name 获取文件名

filename = location.pathname.substring(location.pathname.lastIndexOf("/") + 1);

then by jquery find the anchor tag 然后通过jQuery找到锚标签

$("a[href$="+filename +"]").addClass("selected")

hope this would help you 希望这对您有帮助

For your current html markup, this is the code you'll need in order to achieve the kind of effect you are looking for. 对于当前的html标记,这是实现所需效果所需的代码。

CSS: CSS:

ul li {
    list-style-type:none;
    margin-bottom:10px;
}

a {
    color:Orange;
    font-size:18px;
    font-weight:bold;
}

.active {
    color:red;
}

jQuery: jQuery的:

$(document).ready(function () {
    $("a").click(function (event) {
        $('#navigation ul li a').each(function (index) {
            $(this).removeClass("active");
        });
        $(event.target).addClass("active");
    });
});

You can see this here: http://jsfiddle.net/V5XhN/ 您可以在这里看到: http : //jsfiddle.net/V5XhN/

Hope this helps!!! 希望这可以帮助!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM