首页 > 解决方案 > 如何调试 JavaScript switch 语句错误?

问题描述

我正在尝试创建一个每次加载页面时都会运行一次的函数。

该函数将检查用户在哪个页面(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 代码示例

标签: javascriptif-statementurlswitch-statement

解决方案


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

 window.location.href.indexOf(path)

此外,由于您true在开关中使用 a,因此响应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");
};


推荐阅读