【问题标题】:Creating a dynamic number of buttons with a dynamic URL使用动态 URL 创建动态数量的按钮
【发布时间】:2020-03-06 18:51:12
【问题描述】:

我觉得离这个很近。我只是无法生成在新选项卡中打开的按钮。我被困住了!

     function buildButton(url,i,size) {
            document.write("Building Button with URL= "+url+"<p>");

            var btn = document.createElement("BUTTON");
            btn.appendChild(document.createTextNode("PIDs "+i+" to "+(i+size)));
            btn.setAttribute("href",url);
            btn.setAttribute("target","_blank");
            document.body.appendChild(btn);


}  

【问题讨论】:

  • 嗯,按钮并没有真正的href 属性。对链接使用a(锚)标签。

标签: javascript button tabs


【解决方案1】:

&lt;button&gt;标签改为&lt;a&gt;标签

按钮没有hreftarget 属性,&lt;a&gt; 标签有。代码应该是这样的:

function buildButton(url,i,size) {
  document.write("Building Button with URL= "+url+"<p>");

  var a = document.createElement("a");
  a.appendChild(document.createTextNode("PIDs "+i+" to "+(i+size)));
  a.setAttribute("href",url);
  a.setAttribute("target","_blank");
  document.body.appendChild(a);
}

buildButton('https://stackoverflow.com/', 1, 1);
<!DOCTYPE html>
<html>
<body>

</body>
</html>

【讨论】:

    【解决方案2】:

    解决了:

    function buildButton(url,i,size) {
        var btn = document.createElement("INPUT");
        btn.setAttribute("type","button");
        btn.setAttribute("onclick", "window.open('"+url+"')");
        btn.setAttribute("value","PIDs "+i+" to "+(i+size));
        btn.setAttribute("target","_blank");
        document.body.appendChild(btn);
        document.write("<p>");
    } 
    

    【讨论】:

      【解决方案3】:

      基于此HTML button opening link in new tab 的另一种解决方案。看来你已经想通了

      function buildButton(url,i,size) {
          document.write("Building Button with URL= "+url+"<p>");
      
          var btn = document.createElement("button");
          btn.appendChild(document.createTextNode("PIDs "+i+" to "+(i+size)));
          btn.setAttribute("onclick","window.open('" +url+"', '_blank')");
      
          document.body.appendChild(btn);
      }  
      buildButton("http://www.google.com","Thing", 44) ;
      

      【讨论】:

        猜你喜欢
        • 2014-11-08
        • 2012-02-14
        • 2016-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-30
        • 2017-06-01
        相关资源
        最近更新 更多