2017-03-01 63 views
0

我需要比较我在我的导航栏中的li元素,使用jQuery的网页的网址。如何将当前页面网址与导航栏相匹配?

到目前为止,我有分配给一个变量当前的URL,像这样

var currentPage = window.location.href; 

然后我有一个.each功能检查在导航栏中的所有项目,像这样

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

    } 
); 

现在,我认为我需要一些在函数内部的if语句,也许是这样的?

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

什么我无法弄清楚是什么来比较从列表中的网址?

基本上我想让我在导航栏中突出显示的任何页面。一旦我找出如何让jQuery确认我正在浏览的页面并将其与导航栏进行匹配,我将使用.css更改背景图像,以使我在导航栏上突出显示哪个页面。我在一个jQuery类中,这是分配的东西。

我在这里搜索,我找不到任何真正匹配的东西,我正在尝试做。

希望有人有一些见解...如果这个问题甚至是有道理的,我几乎拉出我的头发只是想这个词成为一个问题,数字少得多了......

回答

1

我想你可能正在寻找:

this.href 

这应该给你你正在循环的标签的实际href。

(答案改善,得益于以下评论)

+1

更容易(和更快一点):'this.href' ... –

+1

这对他的情况也更好,因为它将回退完整的href,而不仅仅是链接的属性值 - 我将编辑答案。 –

+0

是的谢谢你们,我用“这个”效果很棒! –

0

可以使用解析(..)匹配链路是否是当前PAGE电泳演示不能在计算器正常运行,如果你想看到的结果,你应该去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,e.g: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>

+0

我很感激这个帮助,但是这有点凌驾于我的头上,谢谢!有一天我会好起来的。哈哈。我确实弄明白了。 –

0

对于任何人,着眼于这一点,我想通弄明白了,用这个和。每。这是它的样子。

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; 
     } 
    } 
); 

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