How can I add a conditional statement that says something like
if(window.location.href.indexOf("#/brand开发者_StackOverflow社区partners"))
{
$("#brandpartners").addClass("specialbrand");
}
The hash seems to break the statement. Is there a better way?
First of all, you can't use indexOf that way. It returns -1, when it's not found which isn't false.
It makes a lot more sense to me to just use the built-in parsing of the hash value in the location object. I'd suggest doing it this way:
if (window.location.hash == "#brandpartners") {
$("#brandpartners").addClass("specialbrand");
}
I don't know your URL structure, but there shouldn't be a need for a slash after the # for a simple hash value. But, if you insist on using the slash, it would look like this:
if (window.location.hash == "#/brandpartners") {
$("#brandpartners").addClass("specialbrand");
}
The hash (#
) isn't breaking the statement at all for me. But I don't know exactly why you have the /
in there when you don't need it.
var str = "http://stackoverflow.com/questions/6950161#hmenus";
alert(str.indexOf("#hmenus"));
This code alerts 42, which means it should do what you want. I
As @jfriend00 sais, it should be:
if(window.location.href.indexOf("#/brandpartners")!=-1)
{
$("#brandpartners").addClass("specialbrand");
}
indexOf()
returns -1 if the string is not found, which evaluates as "truthy" such that your if
statement isn't doing what you think it is. So try:
if (window.location.href.indexOf("#/brandpartners") != -1) {}
精彩评论