Jquery:如果url包含特定的哈希值,则有条件地添加类

时间:2011-08-05 00:29:22

标签: jquery hash conditional

如何添加类似

的条件语句
if(window.location.href.indexOf("#/brandpartners"))
    {
    $("#brandpartners").addClass("specialbrand");
    }

哈希似乎打破了这个说法。还有更好的方法吗?

4 个答案:

答案 0 :(得分:9)

首先,你不能那样使用indexOf。它返回-1,当找不到它不是假的时候。

使用位置对象中的哈希值的内置解析对我来说更有意义。我建议这样做:

if (window.location.hash == "#brandpartners") {
    $("#brandpartners").addClass("specialbrand");
}

我不知道你的URL结构,但是对于一个简单的哈希值,不需要#之后的斜杠。但是,如果你坚持使用斜杠,它将如下所示:

if (window.location.hash == "#/brandpartners") {
    $("#brandpartners").addClass("specialbrand");
}

答案 1 :(得分:1)

哈希(#)对我来说根本没有违反声明。但是,当你不需要时,我不确切地知道为什么你有/

var str = "http://stackoverflow.com/questions/6950161#hmenus";
alert(str.indexOf("#hmenus"));

此代码警告42,这意味着它应该执行您想要的操作。我

答案 2 :(得分:1)

作为@ jfriend00 sais,它应该是:

if(window.location.href.indexOf("#/brandpartners")!=-1)
            {
$("#brandpartners").addClass("specialbrand");
            }

答案 3 :(得分:1)

如果找不到该字符串,则

indexOf()返回-1,其值为“truthy”,这样您的if语句就不会按照您的想法执行。所以试试:

if (window.location.href.indexOf("#/brandpartners") != -1) {}