开发者

How to add a class active in a three level of menu where href attribute has the same pass

开发者 https://www.devze.com 2023-01-30 12:14 出处:网络
I have three level of submenu created dynamically. I want to add class=\"active\" where the text has the same url.

I have three level of submenu created dynamically. I want to add class="active" where the text has the same url.

A space and comma will be replaced with under score.

For example, Glass, plast, gummi og porselen page will be

http://www.mywebsite.com/folder/Glass_plast_gummi_og_porselen.asp

Each href attribute has the same path as in URL

HTML

<ul id="submenu">
        <ul><li><a href="Grunnskole.asp" title="" class="">Grunnskole</a>


            <ul><li><a href="Forskerspiren.asp" title="" class="">Forskerspiren</a>


            <ul><li><a href="Sikkerhet.asp" title="" class="">Sikkerhet</a>


            </li><li><a href="Laboratorieutstyr(1).asp" title="" class="">Laboratorieutstyr</a>


            </li><li><a href="Glass_plast_gummi_og_porselen.asp" title="" class="">Glass, plast, gummi og porselen</a>


            </li><li><a href="Datalogging.asp" title="" class="">Datalogging</a>


            </li></ul></li><li><a href="Mangfold_in_naturen.asp" title="" class="">Mangfold in naturen</a>


            </li><li><a href="Kropp_og_helse.asp" title="" class="">Kropp og helse</a>


            </li><li><a href="Verdensrommet.asp" title="" class="">Verdensrommet</a>


            </li><li><a href="Fenomener_og_stoffer.asp" title="" class="">Fenomener og stoffer</a>


            </li></ul></li><li><a href="Sikkerhet_og_开发者_开发技巧inventar(1).asp" title="" class="">Sikkerhet og inventar</a>


            </li><li><a href="Laboratorieutstyr.asp" title="" class="">Laboratorieutstyr</a>


            </li></ul>

    </ul>

I thank you in advance.


You can make use of window.location.pathname to obtain just the filename, then use the attribute-ends-with or attribute-equals selectors:

// Get the current file name from window.location.pathname
var file = window.location.pathname.split("/").pop();

// Look for <a> elements whose `href` matches the file 
$("#submenu a[href$='"+file+"']").addClass("active");

Using this method, you don't have the ambiguity that comes from 2 characters being replaced with an underscore.


This works: http://www.jsfiddle.net/BBvLN/. The way you are cleaning up the URL is not correct. Also, you want to match the href of the a tag, not the text contained in the a tag.

var url = "http://www.mywebsite.com/folder/Glass_plast_gummi_og_porselen.asp";
var slug = url.replace('http://www.mywebsite.com/folder/','');

$("#submenu a[href=" + slug + "]").addClass("active");
0

精彩评论

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