简体   繁体   English

如何在jQuery中将URL与href匹配?

[英]How to match URL with href in jQuery?

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). 使用列表导航,我正在寻找一种干净的方法,如果页面URL(减去路径后的任何内容)与列表项的href(减去路径后的所有内容)匹配,则将“ selected”类应用于列表项。

Example: 例:

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

Apply class "selected" to the list item when the page URL includes the /p/clothing/dresses/N-10635 part of the href. 当页面URL包含href的/ p / clothing / dresses / N-10635部分时,将“ selected”类应用于列表项。

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>

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 ). 但是,这仅在URL完全匹配href时才应用“ selected”类 -意味着它必须像href中那样包含链接跟踪变量(即: ?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: 考虑如何匹配“基本” URL和href的方法,我尝试将数据属性添加到列表项以仅匹配路径:

$('.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>

I attempted this with variations of window.location including: window.location.href , window.location.href.pathname , window.location.href.indexOf , window.location.href.startsWith . 我尝试使用window.location的变体进行此操作,包括: window.location.hrefwindow.location.href.pathnamewindow.location.href.indexOfwindow.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. 在此方法不起作用的情况下,我寻求了一种与URL和href的路径匹配的方法,而与其他参数或变量无关,但是我所能找到的是将URL和href专门字符串或参数进行匹配的方法。 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. 我可以找到仅匹配URL或href的一部分的所有实例都使用“ split” RegEx,它引入了我认为我不需要的另一种复杂性。 Am I missing a simpler solution? 我是否缺少一个更简单的解决方案?

you can use indexOf() 您可以使用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');
        }
   });
});

Example

 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> 

Explanation : 说明

$(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'); 
       }
    });
}); 

you can read about .split() here 你可以在这里阅读有关.split()的信息

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回答中,他使用this.href ,它将以字符串形式返回href ..在您的情况下,将返回类似'/ p / clothing / dresses / N-10635?ab = leftNav:dresses'的名称,并且他使用location.pathnameindexOf()的代码,他尝试在href找到location.pathname

Additional : in your case both my answer and Vinas answer will work . 另外在您的情况下 ,我的答案和Vinas的答案都会起作用。 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 那不取决于代码,取决于您的情况和您要执行的操作..类似.hide(0) , .slideUp(0) , fadeOut(0)的那些都隐藏具有相同效果的元素..因此该代码始终由您使用的情况决定。.可能是我的代码,甚至Vinas的代码在另一种情况下也无法使用

I guess if you keep your html like 我想如果你保持你的html一样

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

but change the comparisson to: 但将比较更改为:

$('.leftNav li a').each(function(){
    if (this.href.indexOf(location.pathname) > -1) {
        $(this).parents('li').addClass('selected');
    }
});

you'll get what you need! 您将得到所需的东西!

The "if" above will check if the given path is contained in item's href property. 上面的“ if”将检查给定的路径是否包含在item的href属性中。

So, if your URL is " http://www.yourhost.com/p/clothing/dresses/N-10635?param=value ", it's path (/p/clothing/dresses/N-10635) should be found, and the output for the given example would be: 因此,如果您的网址是“ http://www.yourhost.com/p/clothing/dresses/N-10635?param=value ”,则应找到其路径(/ p / clothing / dresses / N-10635),给定示例的输出为:

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

I hope this helped! 希望对您有所帮助! =) =)

Assuming there isn't any '?' 假设没有任何“?” character in the actual path you could use something like this for both the location and the href: 实际路径中的字符,您可以在位置和href中使用类似这样的内容:

function getBaseURL(url) {
    return url.split('?')[0];
}

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

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