JavaScriptのwindow.locationにtarget =“ _ blank”を追加するには?


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>


では、新しいウィンドウでURLを開きますか?
ムーサ

うん?キーが正しい場合のみ
Flamur Beqiraj 2013

どこでHEAD閉まる?
Lucas

回答:


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 2015年

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>

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.