jQuery 是向菜单项添加活动类的更好主意

发布于 2024-11-06 22:29:19 字数 997 浏览 2 评论 0 原文

当页面的 url = 链接的 href 属性时,这个简单的脚本将“活动”类添加到列表中的链接

var TheP   = window.location.pathname.split('/');
var HeRe   = TheP[TheP.length-1];
$('ul a').each(function(){
 var Link  = $(this).attr('href');
      if (Link == HeRe){ $(this).addClass('active');}
 });

并且它可以工作。但是......仅当 href 属性只是单个文件 href="index.html" 时。在接下来的情况或类似情况下根本不起作用:

<a href="foo/index.html">foo</a>
<a href="../bar/index.html">bar</a>

实际上为了解决它我可以写:

 var TheP = window.location.pathname.split('/');
 var P1   = TheP[TheP.length-1];
 var P2   = TheP[TheP.length-2];
 var HeRe = P2+"/"+P1;

 $('ul a').each(function(){
  var Ln = $(this).attr('href');
  var Ln = Ln.split('/');
  var L1 = Ln[Ln.length-1];
  var L2 = Ln[Ln.length-2];
  var Link = L2+"/"+L1;
      if (Link == HeRe){$(this).addClass('active');}
 });

但是......嗯......我认为应该有一个更好和更灵活的方法。另外,因为只有一个文件作为路径,上面的内容不起作用:(

This simple script adds an "active" class to a link in a list when page's url is = link's href attribute

var TheP   = window.location.pathname.split('/');
var HeRe   = TheP[TheP.length-1];
$('ul a').each(function(){
 var Link  = $(this).attr('href');
      if (Link == HeRe){ $(this).addClass('active');}
 });

And it works. But ... only when the href attribute is just a single file href="index.html". Doesn't work at all in these next cases or similar:

<a href="foo/index.html">foo</a>
<a href="../bar/index.html">bar</a>

Actually to solve it I could write:

 var TheP = window.location.pathname.split('/');
 var P1   = TheP[TheP.length-1];
 var P2   = TheP[TheP.length-2];
 var HeRe = P2+"/"+P1;

 $('ul a').each(function(){
  var Ln = $(this).attr('href');
  var Ln = Ln.split('/');
  var L1 = Ln[Ln.length-1];
  var L2 = Ln[Ln.length-2];
  var Link = L2+"/"+L1;
      if (Link == HeRe){$(this).addClass('active');}
 });

But ... ehm ... I think there should be a better and more flexible way. Also because what is above doesn't work having just a single file as path : (

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心在旅行 2024-11-13 22:29:19

更新:我最初误解了这个问题。重新阅读它,听起来您想要确保匹配所有index.html,而只匹配您所在的特定索引(这使得更多实际上,感觉)。

在这种情况下,您可以这样做:

var path = window.location.href; // Just grabbing a handy reference to it
$('ul a').each(function() {
    if (this.href === path) {
        $(this).addClass('active');
    }
});

...因为 DOM 元素 href 属性(与“href”属性不同) ="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-88517319" rel="nofollow">是绝对路径

实例

显然,您可以做更多的事情来限制初始选择器(在原因),越好。例如,如果这一切都在某个导航结构内,则只有在该结构内工作才会更有效。

另外,如果有很多匹配项,您可以在添加类时避免执行 jQuery 包装器(如果您愿意):

    if (this.href === path) {
        this.className += " active"; // note the space
    }

原始答案

如果 href< /code> 属性在文件名部分之前总是有一个 /,然后:

var TheP   = window.location.pathname.split('/');
var HeRe   = TheP[TheP.length-1];
$('ul a[href$="/' + HeRe + '"]').addClass('active');

使用 属性结尾为选择器来查找相关链接。

如果 href 属性有时可能只是 index.html 或类似的,您可以这样做:

var TheP   = window.location.pathname.split('/');
var HeRe   = TheP[TheP.length-1];
$('ul a[href$="/' + HeRe + '"], ul a[href="' + HeRe + '"]').addClass('active');

...这将捕获带有 / 的属性在它们前面使用“ends-with”选择器,以及使用“equals”选择器进行精确匹配的那些。

Update: I misunderstood the question originally. Re-reading it, it sounds like you want to be sure not to match all index.htmls, but only the specific one you're in (which makes rather more sense, actually).

In that case, you can do this:

var path = window.location.href; // Just grabbing a handy reference to it
$('ul a').each(function() {
    if (this.href === path) {
        $(this).addClass('active');
    }
});

...because the href property (which is not the same as the "href" attribute) of the DOM element is the absolute path.

Live example

Obviously, the more you can do to constrain that initial selector (within reason), the better. For instance, if this is all within some navigation structure, only working within that structure will be more efficient.

Also, if there will be a lot of matches, you can avoid doing the jQuery wrapper when adding the class if you like:

    if (this.href === path) {
        this.className += " active"; // note the space
    }

Original answer:

If the href attributes will always have a / before the filename part, then:

var TheP   = window.location.pathname.split('/');
var HeRe   = TheP[TheP.length-1];
$('ul a[href$="/' + HeRe + '"]').addClass('active');

That uses an attribute ends-with selector to find the relevant links.

If the href attributes may sometimes be simply index.html or similar, you can do this:

var TheP   = window.location.pathname.split('/');
var HeRe   = TheP[TheP.length-1];
$('ul a[href$="/' + HeRe + '"], ul a[href="' + HeRe + '"]').addClass('active');

...which will catch the ones with / in front of them using the "ends-with" selector, and also the ones where there's an exact match using the "equals" selector.

一城柳絮吹成雪 2024-11-13 22:29:19

与其分解路径名,不如直接比较整个路径。如果你有相对网址,那应该很容易。此外,您还可以执行替换来处理绝对网址。

var mainpart = window.location.protocol + "//" + window.location.host;
var path = '/' + window.location.pathname;
$('ul a').each(function(){
    var Link  = $(this).attr('href').replace(mainpart, '');
    if (Link === path || '/' + Link === path){ $(this).addClass('active');}
});

Rather than break up the pathname why don't you just compare the whole thing. If you have relative urls it should be easy. Also, you can perform a replace to deal with absolute urls.

var mainpart = window.location.protocol + "//" + window.location.host;
var path = '/' + window.location.pathname;
$('ul a').each(function(){
    var Link  = $(this).attr('href').replace(mainpart, '');
    if (Link === path || '/' + Link === path){ $(this).addClass('active');}
});
一向肩并 2024-11-13 22:29:19
var TheP = window.location.pathname.split('/');
var HeRe = TheP[TheP.length-1];
$('ul a[href$="' + HeRe + '"]').addClass('active');

根据规范 http://www.w3.org/TR/css3-selectors /#attribute-substrings

提供了三个附加属性选择器,用于匹配属性值中的子字符串:

  • [att^=val] 表示带有
    其值开始的 att 属性
    带有前缀“val”。如果“val”是
    空字符串然后选择器
    不代表任何东西。
  • [att$=val] 表示一个元素
    值结束的 att 属性
    带有后缀“val”。如果“val”是
    空字符串然后选择器
    不代表任何东西。
  • [att*=val] 表示一个元素
    att 属性的值
    至少包含一个实例
    子字符串“val”。如果“val”是
    空字符串,然后选择器执行
    不代表什么。
var TheP = window.location.pathname.split('/');
var HeRe = TheP[TheP.length-1];
$('ul a[href$="' + HeRe + '"]').addClass('active');

According to specification http://www.w3.org/TR/css3-selectors/#attribute-substrings :

Three additional attribute selectors are provided for matching substrings in the value of an attribute:

  • [att^=val] Represents an element with
    the att attribute whose value begins
    with the prefix "val". If "val" is
    the empty string then the selector
    does not represent anything.
  • [att$=val] Represents an element with
    the att attribute whose value ends
    with the suffix "val". If "val" is
    the empty string then the selector
    does not represent anything.
  • [att*=val] Represents an element with
    the att attribute whose value
    contains at least one instance of the
    substring "val". If "val" is the
    empty string then the selector does
    not represent anything.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文