如何在jQuery中将URL与href匹配? [英] How to match URL with href in jQuery?

查看:75
本文介绍了如何在jQuery中将URL与href匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用列表进行导航,我正在寻找一种干净的方法,如果页面URL(减去路径后的任何内容)与列表项目的href(减去后的任何内容)相匹配,则将"selected"类应用于列表项目路径).

Using a list for navigation, I am looking for a clean way to apply the 'selected' class to a list item if the page URL (minus anything after the path) matches the href of the list item (minus anything after the path).

示例:

<li><a href="/p/clothing/dresses/N-10635?ab=leftNav:dresses">dresses</a></li>

当页面URL包含href的/p/clothing/dresses/N-10635 部分时,将选择的"类应用于列表项.

Apply class "selected" to the list item when the page URL includes the /p/clothing/dresses/N-10635 part of the href.

到目前为止,我使用以下方法获得了部分结果:

So far, I achieved partial results using:

$('.leftNav li a').each(function(){
    if(window.location.href == this.href){
        $(this).parents('li').addClass('selected');
    }
});

<ul class="leftNav">
<li><a href="/p/clothing/dresses/N-10635?ab=leftNav:dresses">dresses</a></li>
<li><a href="/p/clothing/bottoms/capris/N-10764?ab=leftNav:capris">capris</a></li>
</ul>

但是,仅当URL与href完全匹配时才应用"selected"类-意味着它必须像href中那样包含链接跟踪变量(即:?ab=leftNav:dresses) .考虑如何匹配基本" URL和href的方法,我尝试将数据属性添加到列表项以仅匹配路径:

This, however, only applied the 'selected' class when the URL matched the href exactly - meaning it had to include the link-tracking variable as in the href (ie: ?ab=leftNav:dresses). Thinking of ways to match the "base" URL's and href's, I tried adding a data attribute to the list items to match the path only:

$('.leftNav li').each(function(){
    if(window.location.href == (this).data('left-nav-href')){
        $(this).addClass('selected');
    }
});

<ul class="leftNav">
<li data-left-nav-href="/p/clothing/dresses/N-10635"><a href="/p/clothing/dresses/N-10635?ab=leftNav:dresses">dresses</a></li>
<li data-left-nav-href="/p/clothing/bottoms/capris/N-10764"><a href="/p/clothing/bottoms/capris/N-10764?ab=leftNav:capris">capris</a></li>
</ul>

我尝试了window.location的变体,包括:window.location.hrefwindow.location.href.pathnamewindow.location.href.indexOfwindow.location.href.startsWith.在此方法不起作用的情况下,我寻求了一种与URL和href的路径匹配的方法,而与其他参数或变量无关,但我能找到的是将URL和href的专门字符串或参数进行匹配的方法. .我可以找到仅匹配URL或href的一部分的所有实例都使用"split" RegEx,这引入了我认为我的使用不需要的另一种复杂性.我是否缺少一个更简单的解决方案?

I attempted this with variations of window.location including: window.location.href, window.location.href.pathname, window.location.href.indexOf, window.location.href.startsWith. With this not working, I searched for a way to match the path of the URL and href regardless of additional parameters or variables, but all I can find are ways to match URL's and href's specifically with strings or parameters. All instances I could find of matching only part of a URL or href use "split" RegEx which introduces another level of complexity that I don't think my use requires. Am I missing a simpler solution?

推荐答案

您可以使用indexOf()

$(document).ready(function () {
    $('.leftNav li a').each(function(){
        var ThisHref = ($(this).attr('href').split('?'))[0];
        if(window.location.href.indexOf(ThisHref) > -1) {
            $(this).closest('li').addClass('selected');
        }
   });
});

示例

var url = "http://www.website.com/index/p/clothing/bottoms/capris/N-10764?ab=leftNav:capris";

$(document).ready(function () {
    $('.leftNav li a').each(function(){
        var ThisHref = ($(this).attr('href').split('?'))[0];
        //alert(ThisHref);
        if(url.indexOf(ThisHref) > -1) {
            $(this).closest('li').addClass('selected');
        }
   });
});

.selected{
  background : red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="leftNav">
<li><a href="/p/clothing/dresses/N-10635?ab=leftNav:dresses">dresses</a></li>
<li><a href="/p/clothing/bottoms/capris/N-10764?ab=leftNav:capris">capris</a></li>
</ul>

说明:

$(document).ready(function () {  // run the code after document is ready
    $('.leftNav li a').each(function(){ // loop through <a> on <li>
       // $(this).attr('href') will return href as string .. in your case will return something like '/p/clothing/dresses/N-10635?ab=leftNav:dresses'
       // using .split('?') to separating this href string by '?'
       // [0] get the first string after split (in this case it will be '/p/clothing/dresses/N-10635')
       // combine all of those steps on just one line
       var ThisHref = ($(this).attr('href').split('?'))[0];
       // get the 'window.location.href' which is return your url ..something like 'http://www.website.com/index/p/clothing/bottoms/capris/N-10764?ab=leftNav:capris'
       // try to find (first string after split) into (url/window.location.href)
       if(window.location.href.indexOf(ThisHref) > -1) { // if the url contains the first string after split addClass
          $(this).closest('li').addClass('selected'); 
       }
    });
}); 

您可以阅读 .split( )

注意:在Vinas回答中,他使用this.href,它将返回href为 字符串..在您的情况下将返回类似 '/p/clothing/dresses/N-10635?ab = leftNav:dresses',他使用 location.pathname indexOf()的代码,他尝试找到location.pathname 进入href

Note: in Vinas answer he use this.href which will return href as string .. in your case will return something like '/p/clothing/dresses/N-10635?ab=leftNav:dresses' and he use location.pathname and the code of indexOf() he try to find the location.pathname into the href

其他:在您的情况下我的答案和Vinas答案都将起作用.那不取决于代码,取决于您的情况和您要执行的操作..诸如.hide(0) , .slideUp(0) , fadeOut(0)之类的所有内容都以相同的效果隐藏该元素..因此,代码始终取决于您使用的情况..可能是我的代码,甚至Vinas的代码也无法在另一种情况下使用

Additional: in your case both my answer and Vinas answer will work . that's not depending on code its depending on your case and what you're trying to do .. something like .hide(0) , .slideUp(0) , fadeOut(0) all of those hide the element with same effect .. So the code always determine by the case you working with .. May be my code or even Vinas's code won't work on another case

这篇关于如何在jQuery中将URL与href匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆