如何将target =“ _ blank”添加到JavaScript window.location?


118

以下将目标设置为_blank

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

但这似乎不起作用。如何在新标签页中启动链接?

这是我的代码:

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>


因此,您想在新窗口中打开一个网址吗?
穆萨

是的!! 仅在钥匙正确的情况下……
Flamur Beqiraj 2013年

哪里HEAD关门?
卢卡斯

Answers:


266

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!");
    }
}

8
@twinlakes在所有现代浏览器中都将其阻止。
Ben Racicot 2015年

@BenRacicot好吧,默认情况下会阻止弹出窗口,并且大多数人都不会更改它
twinlakes

window.open的问题是弹出式阻止程序
jmoran


6

我创建了一个函数,使我可以获得此功能:

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

0

    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>

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.