如何调试JavaScript开关语句错误



我正在尝试创建一个函数,该函数将在每次加载页面时运行一次。

该函数将检查用户所在的页面(url/路径(,然后它将在switch语句中循环一次,如果任何路径名称匹配,则它将向API发送一些信息。

我只收到"没有URL/路径名匹配"。我知道我几乎找到了正确的解决方案。

<script>    
function winLocation(path) {
return window.location.pathname.indexOf(path);
}
console.log(winLocation);
switch (true) {
case winLocation("stack"):
console.log('This is a stack overflow page');
// Fire info to api
break;
case winLocation("google"):
// Fire info to api if url has google in it
break;
default:
console.log("no urls/path names match");
};
</script>

https://codepen.io/bkdigital/pen/eQYQPL-代码的Codepen示例

如果你想检查整个url,那么你需要在函数中使用href而不是pathname

window.location.href.indexOf(path)

此外,由于您在开关中使用true,来自winLocation的响应也应该是布尔值,您可以通过检查它是否不同于-1来实现这一点。

function winLocation(path) {
return window.location.href.indexOf(path) !== -1;
}

那会给你想要的结果。

要查看它,只需运行下面的代码片段:

function winLocation(path) {
return window.location.href.indexOf(path) !== -1;
}
switch (true) {
case winLocation("stack"):
console.log('This is a stack overflow page');
// Fire info to api
break;
case winLocation("google"):
	console.log('This is a google page');
// Fire info to api if url has google in it
break;
default:
console.log("no urls/path names match");
};

最新更新