繁体   English   中英

比较URL字符串和菜单字符串,然后使用jQuery添加类

[英]compare url string and menu string then add class using jquery

我有一个看起来像这样的URL:

http://www.website.co.uk/en-us/aboutus/thegroup/test.aspx

我在页面上有UL LI菜单:

<ul>
    <li><a href="/aboutus/thegroup/test.aspx">Test</a></li>
    <li>Hello</li>
    <li>Bye</li>
    <li>Something</li>
    <li>Cars</li>
</ul>

我在每个页面上都有菜单,并且想使用jquery在该页面上检查即时消息。 如果是,则将A / li设为粗体,以便用户知道它们在页面上。

我尝试了以下方法:

$(document).ready(function () {
  if(window.location.href.indexOf("test")) // 
     {
        alert("your url contains the name test");
     }
});

但是id就像不涉及对URL字符串的值进行硬编码的事情一样。 仿佛用户决定向UL / LI添加更多链接,jQuery需要自动检查链接和url,并向LI添加类(以便我可以为其设置样式)。

希望多数民众赞成在足够的信息。

问题是因为找不到值时indexOf()方法返回-1 您需要检查该值,而不是像当前那样将结果强制为布尔值。 尝试这个:

$(document).ready(function () {
    var loc = window.location.href;
    $("ul a").each(function() {
        if (loc.indexOf($(this).attr("href")) != -1) {
            $(this).addClass("current");
        }
    });
});

您需要使选择器更具体一些,例如#menu a

这个?

$('ul#menu a').each(function() {
   if(window.location.href.indexOf($(this).attr('href')) !== -1) {
      $(this).closest('li').addClass('yourClass');
   }
});

我在您的ul添加了一个id menu以使您的菜单栏与可能在同一页面中的其他ul基本区分开。 !== -1因为indexOf如果找不到在参数中搜索的字符串, indexOf返回-1。

如果不包含字符串, indexOf返回-1:

(document).ready(function () {
  if(window.location.href.indexOf("test") != -1) // 
     {
        alert("your url contains the name test");
     }
});
$(document).ready(function () {
  var liTest = $('ul > li'); // ' was missing
  liTest.each(function() {
     if(window.location.href == $('a', this).attr('href')) // 
     {
        $(this).css('font-weight', 'bold');
        return;
     }
  });
});

暂无
暂无

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

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