检查 ANY url 是否为真
Checking whether ANY url is true
我是 Javascript 和 Jquery 的新手,但不知道我做错了什么。我只想检查用户是否在 3 个 URL 中的任何一个上。我只想检查用户是否在关于我们、MEMSTAFF 团队或职业部分。这就对了。我认为如果我只使用 OR (||) 运算符,这应该可以。我做错了什么?
<script type="text/javascript">
$(document).ready(function() {
// Check if any of these relative URLS are true
if(window.location.href.indexOf("/about-us" || "/memstaff-team" || "/careers") > -1) {
// Alert me if I am in one of the MAIN sections
alert("Your are in one of the MAIN sections");
}
});
</script>
测试
if (window.location.href.indexOf("/about-us" || "/memstaff-team" || "/careers") > -1)
相当于做
temp = "/about-us" || "/memstaff-team" || "/careers";
if (window.location.href.indexOf(temp) > -1)
由于 ||
运算符只是 returns 第一个真值,它实际上是在做 temp = "/about-us"
并且只是对此进行测试。 "OR" 表达式不会自动分配,您需要明确分配。
if (window.location.href.indexOf("/about-us") > -1 ||
window.location.href.indexOf("/memstaff-team") > -1 ||
window.location.href.indexOf("/careers") > -1)
但更简单的方法是使用正则表达式:
if (window.location.href.match(/\/(about-us|memstaff-team|careers)/))
这是另一种方法:
const urls = ["/about-us", "/memstaff-team", "/careers"];
if (urls.some(url => window.location.href.indexOf(url) > -1)) {
alert("...");
}
我是 Javascript 和 Jquery 的新手,但不知道我做错了什么。我只想检查用户是否在 3 个 URL 中的任何一个上。我只想检查用户是否在关于我们、MEMSTAFF 团队或职业部分。这就对了。我认为如果我只使用 OR (||) 运算符,这应该可以。我做错了什么?
<script type="text/javascript">
$(document).ready(function() {
// Check if any of these relative URLS are true
if(window.location.href.indexOf("/about-us" || "/memstaff-team" || "/careers") > -1) {
// Alert me if I am in one of the MAIN sections
alert("Your are in one of the MAIN sections");
}
});
</script>
测试
if (window.location.href.indexOf("/about-us" || "/memstaff-team" || "/careers") > -1)
相当于做
temp = "/about-us" || "/memstaff-team" || "/careers";
if (window.location.href.indexOf(temp) > -1)
由于 ||
运算符只是 returns 第一个真值,它实际上是在做 temp = "/about-us"
并且只是对此进行测试。 "OR" 表达式不会自动分配,您需要明确分配。
if (window.location.href.indexOf("/about-us") > -1 ||
window.location.href.indexOf("/memstaff-team") > -1 ||
window.location.href.indexOf("/careers") > -1)
但更简单的方法是使用正则表达式:
if (window.location.href.match(/\/(about-us|memstaff-team|careers)/))
这是另一种方法:
const urls = ["/about-us", "/memstaff-team", "/careers"];
if (urls.some(url => window.location.href.indexOf(url) > -1)) {
alert("...");
}