我想做类似的事情:如果URL包含" type = dections"做某事。
我有以下代码:
var url = $(location).attr('href');
if(url.index("type=department") >= 0){
do something
}
但我的控制台写信给我: und typeerror:url.index不是函数
怎么了?
没有作为 index()
的功能,您需要 String.prototype.indexOf()
if(url.indexOf("type=department") >= 0){
//Do something
}
您也可以使用String.prototype.includes()
includes()
方法确定是否可以在另一个字符串中找到一个字符串,返回true
或false
。
if(url.includes("type=department")){
//Do something
}
我在想当您说URL时,您的意思是您的浏览器URL ...如果是这样,那么您应该做的就是这样。
function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
}
所以您将如何处理该功能...
说您的URL是http://www.example.com?type=department,您将执行以下...
var type = getUrlParameter('department');
if(type!=undefined){
do something here ...
}
如有疑问,请在文档中查找它:
.attr( attributeName )
返回:字符串
,由于返回类型是一个很好的旧JavaScript字符串,而不是jQuery对象,因此您可以使用标准的JavaScript文档,在其中我们看不到任何index()
方法的跟踪。但是,我们看到了几种查找子字符串的方法,例如indexof():
字符串对于持有可以在文本中表示的数据很有用 形式。字符串上一些最常用的操作是检查他们的 长度,使用 和 =字符串来构建和连接它们 运营商,检查是否存在或 indexof()方法,或用substring()提取子字符串 方法。