简体   繁体   中英

Replace href/add attribute in external page to be relevant to current url

So I have a navigation html that gets loaded into every page across a site, it looks like this:

<div id="links-row">
    <ul class="cssmenu">
        <li class="home"><a title="Home" href="../"></a></li>
        <li class="sale"><a title="Sale" href="../sale"></a></li>
        <li class="news"><a title="News" href="../news">
        <li class="contact"><a title="Contact" href="../contact"></a></li>
    </ul>
</div>

It gets loaded into pages with js:

$(function(){
    $("#navigation").load("../_nav.html");
});
<div id="navigation">
</div>

I can highlight links individually by setting the class of <a> to "Selected". What I would like to do is add the class attribute and change the href to "#" instead of the existing url based on the current page. I know I can get the current page name via js with:

path = window.location.pathname;
page = path.replace(/\//g,"");

My question is; how can I search the loaded page to find the relevant link and then change that specific links url href and set it's class

Thanks for the input here's the result.

$(function(){
    path = window.location.pathname;
    page = path.replace(/\//g,"");
    $("#nav-placeholder").load("../_nav.html", function() {
        $('a[href="../' + page + '"]').addClass("Selected").attr("href", "#")
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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