2

我有一个如下所示的 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 添加一个类(以便我可以设置它的样式)。

希望那是足够的信息。

4

4 回答 4

4

问题是因为找不到该值时该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

于 2012-04-18T10:25:47.553 回答
2

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

(document).ready(function () {
  if(window.location.href.indexOf("test") != -1) // 
     {
        alert("your url contains the name test");
     }
});
于 2012-04-18T10:26:17.040 回答
2

这个?

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

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

于 2012-04-18T10:25:15.070 回答
1
$(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;
     }
  });
});
于 2012-04-18T10:26:08.017 回答