javascript - 如何调试 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 代码示例
解决方案
如果你想检查整个 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");
};
推荐阅读
- c# - 在 C# 中使用 Moq 模拟服务
- javascript - 如何使用函数从变量中切换值
- javascript - 如何在 ES6 或 Javascript 中不受我们控制的 settimeout 函数之后触发函数?
- angular6 - 在不使用组件类中的字段的情况下更新 HTML - 无状态方式
- firebase - 使用 Angular Fire 监听 Firestore 元数据更改
- linq - 将 SQL 查询转换为 LINQ 以获取列值作为 xml 字符串
- java - 如何将 Intellij 从 64 位切换到 32 位
- reactjs - 如何在 React JS 上安全地使用 secretAccessKey
- c - 在C中读取txt时如何删除多余的换行符
- typescript - 为什么我的 jasmine 使用 ngOnInit 中的方法测试组件确实失败了?