document.referrer如果语句不起作用

时间:2019-07-24 14:58:46

标签: javascript if-statement conditional-statements

document.referrer条件语句始终将前一个语句显示为true,但不应该如此

if (document.referrer == "https://parks.com/parks/falls" || "https://parks.com/parks/events/falls" || "https://parks.com/parks/promotions/falls" || "https://parks.com/parks/go-green/falls" || "https://parks.com/parks/info/falls") { 
console.log("Don't Show Modal - coming from a Falls page", document.referrer);
} else {
console.log("Show Modal - coming from some other Page", document.referrer);
$( window ).on('load', function() {
   console.log("modal firing");
   $('#modal').modal({
   backdrop: 'static',
   keyboard: false,
   show: true
   });
});
}

当用户从“瀑布”页面进入网页时,不应显示模式。如果用户从“瀑布”页面以外的任何页面进入网页,则应该显示模式。

3 个答案:

答案 0 :(得分:2)

您的情况不正确。 您应该在每个“子条件”中将变量与常量进行比较。

if (document.referrer == "https://parks.com/parks/falls"
|| document.referrer == "https://parks.com/parks/events/falls"
|| document.referrer == "https://parks.com/parks/promotions/falls" 
|| document.referrer == "https://parks.com/parks/go-green/falls"
|| document.referrer == "https://parks.com/parks/info/falls") {

也许更短:

const domains = ["https://parks.com/parks/cummins-falls", "https://parks.com/parks/events/falls", "https://parks.com/parks/promotions/falls", "https://parks.com/parks/go-green/falls", "https://parks.com/parks/info/falls"];
if (domains.includes(document.referrer)) {

获得IE支持

if (domains.indexOf(document.referrer) !== -1) {

答案 1 :(得分:2)

这是您的if子句实际返回的内容:

// prints "https://parks.com/parks/events/falls"
console.log(document.referrer == "https://parks.com/parks/cummins-falls" || "https://parks.com/parks/events/falls" || "https://parks.com/parks/promotions/falls" || "https://parks.com/parks/go-green/falls" || "https://parks.com/parks/info/falls") 

之所以会这样,是因为使用OR运算符(||),如果无法将左侧表达式强制转换为true,则它将在右侧返回该表达式。

因此,在您的情况下,document.referrer == "https://parks.com/parks/cummins-falls"的计算结果为false,因此它返回的"https://parks.com/parks/events/falls"的结果在Java语言中通过布尔运算的结果为true,因此它返回表达式在该OR运算符及其后的OR运算符中。

有关详细信息,请参见truthy concept上的文档。

您真正想要的是什么

var falls = ["https://parks.com/parks/cummins-falls",  "https://parks.com/parks/events/falls", "https://parks.com/parks/promotions/falls", "https://parks.com/parks/go-green/falls", "https://parks.com/parks/info/falls"];

console.log(falls.indexOf(document.referrer) > -1);

答案 2 :(得分:1)

您的条件不正确。 您应该使用此:

if (document.referrer == "https://parks.com/parks/cummins-falls" || document.referrer == "https://parks.com/parks/events/falls" || document.referrer == "https://parks.com/parks/promotions/falls" || document.referrer == "https://parks.com/parks/go-green/falls" || document.referrer == "https://parks.com/parks/info/falls") { 
    console.log("Don't Show Modal - coming from a Falls page", document.referrer);
} else {
    console.log("Show Modal - coming from some other Page", document.referrer);
}