如何根据当前网址添加类 [英] How to add class based on current url

查看:206
本文介绍了如何根据当前网址添加类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var search_name = position.search; 
if(search_name.search(cate_no = 24)> 0){
$(。cate_new a)。addClass(active);
}
});

如果当前文档URL为 http://abc.com/list.html?cate_no=24
我想将类active添加到li a中。



我搜索并找到了这些js代码,但它不工作。
是不是?

解决方案

搜索( ) 如果找到匹配,则返回匹配的偏移位置,如果找不到匹配,则返回 -1 。 >

正在检查 cate_no = 24 是否包含 cate_no = 24



目前,您的条件检查 search()将返回> 0 ,这不是你想要的。



你应该做的是检查是否更大< strong >> -1 :

如果(search_name.search(cate_no = 24)> -1,则:


虽然使用 会更好更快速。 indexOf() search()表达式,而不是简单的字符串搜索)。

  if(search_name.indexOf(cate_no = 24)> -1)


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?

解决方案

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 contains cate_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:

if (search_name.search("cate_no=24") > -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).

if (search_name.indexOf("cate_no=24") > -1) 

这篇关于如何根据当前网址添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆