繁体   English   中英

如何将当前页面的网址与导航栏匹配?

[英]How to match current page url with nav bar?

我需要将导航到的页面的URL与导航栏(使用jQuery)中的li元素进行比较。

到目前为止,我已经将当前网址分配给了一个变量,就像这样

var currentPage = window.location.href;

然后我有一个.each函数,检查导航栏中的每个项目,像这样

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

    }
);

现在,我假设我需要在函数内部使用某种if语句,也许是这样的?

if(currentPage === ????) {};

我不知道是什么比较列表中的url?

基本上,我想在导航栏中突出显示我正在浏览的任何页面。 一旦我弄清楚如何让jQuery确认我在哪个页面上并将其与导航栏匹配,我将使用.css更改背景图像,以使我站在导航栏上的哪个页面脱颖而出。 我在jQuery类中,这已分配。

我在这里四处搜寻,但找不到我要尝试的真正匹配的东西。

希望有人能提供一些见识...如果这个问题甚至有意义,我实际上是在拔头发,只是想将其表达为一个问题,更不用说弄清楚了...

我认为您可能正在寻找:

this.href

那应该给您您正在循环的标签的实际href。

(答案有所改善,感谢以下评论)

您可以使用parse(..)来匹配链接是否为当前页面。该演示无法在stackoverflow中正确运行,如果要查看结果,则应转到codepen

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <style> a { color: #000; } a.active { color: red; } </style> <nav> <ul> <li><a href="?home">Home</a></li> <li><a href="?contact">Contact</a></li> <li><a href="?about">About</a></li> <li><a href="?contact#hash">Contact Us</a></li> </ul> </nav> <script> function parse(url) { var parts = url.match(/^([^#?]*?)?(\\?.*?)?(#.*)?$/); return { uri: parts[1], search: parts[2], hash: parts[3], /** * * @param that <b>string</b>/<b>object</b> has `href` property,eg:location * @param hash skip hash matching * @param search skip search matching * @returns {boolean|*} if url matched return `true`,otherwise return `false`. */ match: function (that, hash, search) { var self = this, that = parse(typeof that == 'string' ? that : that.href); return (!self.uri || self.uri == that.uri) && (search || self.search == that.search) && (hash || self.hash == that.hash); } }; } $('nav li a').each(function () { console.log(['matching with ', this.href, '===>', parse(this.href).match(location)].join(' ')); console.log(['matching with ', $(this).attr('href'), '===>', parse($(this).attr('href')).match(location)].join(' ')); if (parse($(this).attr('href')).match(location/*,true*/))//remove comment and try the result. $(this).addClass('active'); }); </script> 

对于任何看这个的人,我都知道使用this和.each。 这是它的样子。

var currentPage = window.location.href;

$("nav ul li a").each(
    function() {
        console.log($(this).attr("href"));
        if (currentPage.indexOf($(this).attr("href")) !== -1){
            $(this).addClass("highlight");
            return false;
        }
     }
);

当我第一次尝试解决这个问题时,我还很遥远,我想我误解了我的老师,并且正在思考这个问题。 无论如何,这很好。

暂无
暂无

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

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