首页 > 解决方案 > javascript:遍历案例

问题描述

下面的函数检查父 URL 以查看字母 'pid' 是否存在于父 URL 的查询字符串中。(它位于跨域 iFrame 中)。下面的函数在 Chrome 中的 iFrame 中有效,但在 Safari 和 IE 中无效。

在 Safari 和 IE 中,它似乎忽略了“document.referrer”,而是使用 document.location、document.location.href、window.location、window.location.href 和 document.documentURI 来识别它是否存在于父 URL。

我想循环或循环遍历这些中的每一个,查看 URL 以查看它是否包含带有字母“PID”的查询字符串。在进入我的 else 或 default 之前,如何最好地检查每一个?

function colorchange() {
var match = /\?.*?pid/.test(document.referrer);

if (match) {
     console.log("pid pm");
  } else {
     console.log("standard pm");
  }
}

colorchange();

标签: javascriptswitch-statement

解决方案


您可以拥有一系列预期的对象并遍历它们以找到匹配项。

这是您可以尝试的伪代码。

var pid_testers = [
  window.location.href,
  document.referrer,
  ..
];

var match = pid_testers.some(function (val) {
  if(... logic ..) {
    return val;
  }
});

// This will break when it finds a match..


推荐阅读