var search_name = location.search;
if (search_name.search("cate_no=24") > 0) {
$(".cate_new a").addClass("active");
}
});
If current document url is http://abc.com/list.html?cate_no=24, I want to add class "active" into li a.
I searched and found these js code, but it doesn't work. Is it wrong?
Try this
search
will only gives you the String. that will be in your case?cate_no=24
So we leave the first part as it is and try to find the desired value in
search_name
as string.This how we can find the index of the desired pattern.
It's incorrect.
search()
returns the offset position of a match if a match is found, and -1 if a match isn't found.As you are checking for whether
cate_no=24
containscate_no=24
, it will return 0 if true.Currently, your conditional checks whether the
search()
will return > 0, which is not what you want.What you should be doing is check whether it is greater > -1:
Although, as I mentioned in the first revision of my answer, it would be better and faster to use
indexOf()
(search()
is supposed to be used when dealing with regular expressions, not for simple string searches).My personal blog is static so I also had to figure out how to do this without PHP or some other server side code.
This bit of code grabs the path of the current URL, e.g. if you are on http://example.com/about, it would return the string
'/about/'
. From there you write a simple conditional to add a class to the link you select.This could be further developed to grab the href attributes from an array of links with a certain class (
.nav-items
, for example) and add the active class to whichever element has a href equal to the returned string.