簡體   English   中英

使用JavaScript在另一個窗口中打開鏈接

[英]Open links in another window with javascript

假設我只有一個HTML頁面,其中包含數百個鏈接。 當任何人單擊它們時,這些鏈接將加載在同一窗口中。

我希望它在另一個窗口中打開。 我知道我可以為每個鏈接使用target

<a href="http://www.example1.com/" target="_blank">My Text1</a>
<a href="http://www.example2.com/" target="_blank">My Text2</a>
<a href="http://www.example3.com/" target="_blank">My Text3</a>

Howeder,如果可能的話,我寧願使用JavaScript。 使用JavaScript可以做到這一點嗎?

是的。 使用這樣的東西:

var newtab = window.open('http://www.example1.com/', '_blank');

newtab.focus();

這可能會在新選項卡或新窗口中打開,具體取決於特定的瀏覽器,但我不知道一種更具體地控制它的方法。

編輯或者您是否正在要求一種方法來設置頁面上所有鏈接的行為? 然后,您可以在頁面加載時向所有對象添加適當的目標。

使用jQuery: http : //jsfiddle.net/b8hdv/

$(document).ready(function() {
    $('a').attr('target', '_blank');
});

...或沒有jQuery: http : //jsfiddle.net/uFvUS/

window.onload = function(e) {
    var links = document.getElementsByTagName('a');

    for (var i = 0; i < links.length; i++) {
        links[i].target = '_blank';
    }
}
function open_in_new_tab(url )
{
  var win=window.open(url, '_blank');
  win.focus();
}

像這樣使用:

$("#a_id").on("click", function(){
open_in_new_tab($(this).attr("href"));
});

演示HTML:

<a href="somepage.html" id="a_id">Click me!</a>

這里找到

嘗試這個:

window.open('http://www.example1.com');

並捕獲事件點擊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM