如何添加类似
的条件语句if(window.location.href.indexOf("#/brandpartners"))
{
$("#brandpartners").addClass("specialbrand");
}
哈希似乎打破了这个说法。还有更好的方法吗?
答案 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) {}