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

compare url string and menu string then add class using jquery

本文关键字:字符串 jQuery 添加 URL 菜单 比较 然后      更新时间:2023-09-26

我有一个看起来像这样的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 检查该页面上的 im。如果我是,那么将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 返回 -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;
     }
  });
});