【问题标题】:How to open new tab just once using javascript如何使用javascript只打开一次新标签
【发布时间】:2020-10-23 17:01:09
【问题描述】:

我是 javascript 新手。我想要一个 javascript 代码,当您单击任一按钮时,只允许为链接打开新选项卡一次,但当您单击相同按钮或其他按钮时,脚本将无法工作。对于示例:单击下载或打印按钮后,我想打开我的 facebook 页面的新标签,但我只想打开一次,所以如果该用户单击下载按钮,就是这样。所以即使他多次单击同一个按钮或其他打印按钮多次 facebook 功能根本不起作用

function facebook() {
  window.open("https://www.facebook.com");
}
<button onclick="facebook();printContent('exportContent')"  >Print</button>
<button onclick="facebook();Download();" >Download</button>

我尝试在按钮中使用this.onclick=null,但它会导致两个问题:1/ 它使其他功能只工作一次,而我希望其他功能在每次单击按钮时继续工作,而 facebook 功能只工作一次; 2/当点击其中一个按钮时,新标签打开,当您点击其他按钮时,它仍然打开。

【问题讨论】:

标签: javascript jquery


【解决方案1】:

您可以创建一个全局变量来跟踪您调用 facebook 函数的次数

var counter = 0;

function facebook() {
  if(counter === 0) {
    window.open("https://www.facebook.com");
    counter += 1;
  }
}

function Download() {
  console.log('dl')
}

function printContent(msg) {
    console.log(msg)
}
<button onclick="facebook();printContent('exportContent')"  >Print</button>
<button onclick="facebook();Download();" >Download</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 2021-11-24
    • 2019-08-17
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多