在新 window 中打开 link

Open link in new window

我尝试了各种方法在 .ftl 文件中导入的 .js 文件中打开 link in new window,但没有成功。

下面是.js中的代码

$(".termsAndCondition").on("click", function() {
  var web_url = localStorage.getItem("webUrl");
  setTimeout(() => {
    window.location.href = `${web_url}TermsAndConditions`.prop(
      "target",
      "_blank"
    );
  }, 1000);
});
  1. localStorage return 字符串 - 将字符串 ${web_url}TermsAndConditions 解析为带有 prop 的对象的字符串是什么?
  2. window.location.href 在同一个 window 中打开 URL,您可以使用 window.open,但这可能会触发弹出窗口拦截器
  3. 为什么超时?

只需使用 link 和 target="_blank"

<a href="termsandconditions.html" target="_blank">Terms and conditions</a>

这不是有效的 JS

window.location.href = `${web_url}TermsAndConditions`.prop(
  "target",
  "_blank"
);

我想你要找的是 window.open() (https://developer.mozilla.org/en-US/docs/Web/API/Window/open)。你可以这样调用

window.open('termsandconditions.html');

在你的 javascript 中。此方法也是一种用于在新选项卡中打开 window 的普通 JS 方式。目标可以设置如下:

window.open('URL','TARGET');

其中 TARGET 可以留空(与第一个示例一样)以使用新的 window 打开,设置为 _self 以在相同的 window 中打开,等等

您可以使用 window.open() 方法,如下所示,

$(".termsAndCondition").on("click", function() {
  var web_url = localStorage.getItem("webUrl");
  window.open(`${web_url}TermsAndConditions`, "_blank");
});

或者如下所示的自删除锚标签,

$(".termsAndCondition").on("click", function() {
  var web_url = localStorage.getItem("webUrl");
  var a = $("<a>").appendTo(document.body).attr({
    href: `${web_url}TermsAndConditions`,
    target: "_blank"
  });
  a.get(0).click();
  a.remove();
});

现在问题已通过 target="_blank" 解决,天哪,整个下午我都在处理错误的文件。我从中间的另一个开发人员那里接管了它,我们实际上正在维护具有 2 个开发环境的 2 个项目,我把 1 个误认为是另一个。感谢@mplungjan、@Finn_Lancaster、@Wazeed。