简体   繁体   English

将锚标签与特定的href匹配

[英]Match anchor tag with a specific href

I have a dashboard with a sidebar with navigation links where I highlight each link on the side once you go to the link. 我有一个带有带有导航链接的侧边栏的仪表板,当您转到该链接时,会在侧面突出显示每个链接。 I match the link by doing this 我通过这样做来匹配链接

$(function() {
    var item = $('.sidebar-menu a[href="' + location.href + '"]');

    item.parent().addClass('active');
});

But the problem is if you add an hash (#) to the address then it no longer matches the link. 但是问题是,如果您在地址中添加了哈希(#),则该哈希不再与链接匹配。 And I want it to match it regardless. 而且我希望它与之匹配。

Currently it would match: 目前它会匹配:

  • mysite.com/students/companies mysite.com/students/companies

But it wouldn't match: 但这不匹配:

  • mysite.com/students/companies# mysite.com/students/companies#
  • mysite.com/students/companies/subpage mysite.com/students/companies/subpage

I want it to match anything that includes "mysite.com/students/companies" 我希望它匹配包含“ mysite.com/students/companies”的所有内容

I think you got problem because your anchor tag look something like that: 我认为您遇到了问题,因为您的锚标签看起来像这样:

<a href='somethingelse.php'>Something Else</a>

I notice that you call parent div so.. you wrap your anchor tag by div or ul,li or something else.. 我注意到您称父div为..您通过div或ul,li或其他方式包装锚标签。

What you can do simple add some extra data like 'data-user='' so <div data-user='companies'><a href='somethingelse.php'>Something Else</a></div> 您可以简单地添加一些额外的数据,例如'data-user =',因此<div data-user='companies'><a href='somethingelse.php'>Something Else</a></div>

So now if somebody will be inside companies or something else just do the trick: 因此,现在,如果有人将进入公司内部或进行其他活动,请执行以下操作:

var url_string = window.location.href;
var url = url_string.split('/')
var item = $('div[data-user='+url[3]+']).addClass('active');

That will work for webpage look like: www.some.com/companies and www.some.com/companies/sometihng even www.some.com/companies/sometihng/more 这将适用于以下网页:www.some.com/companies和www.some.com/companies/sometihng甚至www.some.com/companies/sometihng/more

Have a try with 尝试一下

$('.sidebar-menu a').filter(function() {
  return location.href.indexOf(this.href)!=-1;
}).parent().addClass('active');

var item = $('.sidebar-menu a[href*="' + location.pathname + '"]');

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

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