如何将 target="_blank" 添加到 JavaScript window.location?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18476373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:03:39  来源:igfitidea点击:

How to add target="_blank" to JavaScript window.location?

javascript

提问by Flamur Beqiraj

The following sets the target to _blank:

以下将目标设置为_blank

if (key == "smk") {
    window.location = "http://www.smkproduction.eu5.org";
    target = "_blank";
    done = 1;
}

But this doesn't seem to work. How do I launch the link in a new tab?

但这似乎不起作用。如何在新选项卡中启动链接?

Here is my code:

这是我的代码:

function ToKey() {
  var done = 0;
  var key = document.tokey.key.value;
  key = key.toLowerCase();
  if (key == "smk") {
    window.location = "http://www.smkproduction.eu5.org";
    target = "_blank"
    done = 1;
  }
  if (done == 0) {
    alert("Kodi nuk ?sht? valid!");
  }
}
<form name="tokey">
  <table>
    <tr>
      <td>Type the key</td>
      <td>
        <input type="text" name="key">
      </td>
      <td>
      </td>
      <td>
        <input type="button" value="Go" onClick="ToKey()">
      </td>
  </table>
</form>

回答by twinlakes

window.locationsets the URL of your current window. To open a new window, you need to use window.open. This should work:

window.location设置当前窗口的 URL。要打开一个新窗口,您需要使用window.open. 这应该有效:

function ToKey(){
    var key = document.tokey.key.value.toLowerCase();
    if (key == "smk") {
        window.open('http://www.smkproduction.eu5.org', '_blank');
    } else {
        alert("Kodi nuk ?sht? valid!");
    }
}

回答by Eric Sanchez

Just use in your if (key=="smk")

只需在您的 if (key=="smk")

if (key=="smk") { window.open('http://www.smkproduction.eu5.org','_blank'); }

回答by mcems7

I have created a function that allows me to obtain this feature:

我创建了一个允许我获得此功能的函数:

function redirect_blank(url) {
  var a = document.createElement('a');
  a.target="_blank";
  a.href=url;
  a.click();
}

回答by u5819157

    var linkGo = function(item) {
      $(item).on('click', function() {
        var _$this = $(this);
        var _urlBlank = _$this.attr("data-link");
        var _urlTemp = _$this.attr("data-url");
        if (_urlBlank === "_blank") {
          window.open(_urlTemp, '_blank');
        } else {
          // cross-origin
          location.href = _urlTemp;
        }
      });
    };

    linkGo(".button__main[data-link]");
.button{cursor:pointer;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<span class="button button__main" data-link="" data-url="https://stackoverflow.com/">go stackoverflow</span>