开发者

Comparing URL to links

开发者 https://www.devze.com 2023-03-08 12:36 出处:网络
I have the f开发者_高级运维ollowing HTML: <ul class=\"vertical_menu no_select\"> <li class=\"edge_top\">&nbsp;</li>

I have the f开发者_高级运维ollowing HTML:

<ul class="vertical_menu no_select">
    <li class="edge_top">&nbsp;</li>
    <!-- Menu Items Here     -->
    <li class="not_selected"><a class="selection_link" href="index.htm">Home</a></li>
    <li class="not_selected"><a class="selection_link" href="index.htm">Subitem 1</a></li>
    <li class="not_selected"><a class="selection_link" href="index.htm">Subitem 2</a></li>
    <!-- Menu Items End Here -->
    <li class="edge_bottom">&nbsp;</li>
</ul>

Now, the links with the class "selection_link" need to have the li element (their parent) to have a new class "selected" if the current url matches the href value inside of the anchor tag. I can get the full URL but I don't know how to use that to help seeing as there could be more than one page with the same name at different directory levels.

Thanks if you can help! I'm using jQuery with all of this so feel free to provide me with jQuery examples!


Check out the jsFiddle. This should do the trick:

$("ul.vertical_menu li a").each(function() {

    if (this.href == window.location.href) {
        $(this).parent().toggleClass("not_selected selected");
    }

});


$('.selection_link').each(function() {
    if($(this).attr('href') === window.location.pathName.substring(1)) {
        $(this).parent().attr("class", "selected");
    }
});

not tested, but it'll it should start you off. substring is because pathname starts with '/' you could just put that in your href's too


or this...

$('.vertical_menu a').each(function() {
    if (location.href.search(this.attr('href')) != -1) {
        $(this).parent().addClass('selected');
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消