比较url字符串和菜单字符串然后使用jquery添加类

时间:2012-04-18 10:22:38

标签: javascript jquery css

我的网址如下:

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添加一个类(这样我就可以设置样式)。

希望有足够的信息。

4 个答案:

答案 0 :(得分:3)

问题是因为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

答案 1 :(得分:2)

此?

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

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

答案 2 :(得分:2)

如果字符串未包含,

indexOf将返回-1:

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

答案 3 :(得分: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;
     }
  });
});