2012-09-02 90 views
18

I have a bunch of <a href=".html"> links and want to make them all open in new windows.有沒有辦法打開所有<a href> links on a page in new windows?

I know I can do a search and replace all to add target="_blank" to all my <a href="..."> links.

However, is there a quick way, such as setting a CSS style, or adding some JavaScript code, to accomplish the same thing?

+2

您可以搜索並替換您的項目。 – Krycke

+1

重構總是比變通方法更好。從長遠來看,你可以節省很多工作。所以只要做一個搜索和替換,而不是引入一些JavaScript解決方案,這又會減慢你的頁面速度。 – Christoph

+1

我說我知道我可以做一個搜索和替換-_- –

回答

24

If you have a page consisting of only links, consider <base target="_blank">。這將打開一個新窗口的每一個環節(也包括形式的目標,除非<form target="_self">覆蓋。

正如其他人顯示,而無需修改HTML源代碼,您可以使用JavaScript來iterate through all <a> tags and add the target attribute或添加event listener that sets the target attribute dynamically

openInWindow(URL)使用:

你也可以打開替換從網址到JavaScript的所有鏈接的HREF的);

+1

這是最棒的。 BASE TARGET是我所需要的。謝謝!將很快接受。 –

7

CSS: No.
JavaScript: Delegate a click event, which adds a target="_blank" attribute on click of a link.

document.body.addEventListener(function(e) { 
    if (e.target.nodeName.toUpperCase() === 'A' && e.target.href) { 
     e.target.target = '_blank'; 
    } 
}, true); 

Note: If the <a> element contains other elements, you might want to traverse the tree to find out whether an anchor element is clicked:

document.body.addEventListener(function(e) { 
    var target = e.target; 
    do { 
     if (target.nodeName.toUpperCase() === 'A' && target.href) { 
      target.target = '_blank'; 
      break; 
     } 
    } while (target = target.parentElement); 
}, true); 

Or, if you're a jQuery-lover:

$('body').on('click', 'a', function(e) { 
    e.target.target = '_blank'; 
}); 
24

If you have jQuery it's simple

$("a").attr("target", "_blank"); 

Or regular Javascript

var links = document.links; 
for (var i = 0; i < links.length; i++) { 
    links[i].target = "_blank"; 
} 

As per @Lekensteyn's suggestion, without Javascript (added for Completeness)

<base target="_blank">. 
+1

而不是'getElementsByTagName(「a」)'你應該使用'document.links'。這樣做的好處是您只包含鏈接(即「」元素),而不是像'。 – Lekensteyn

+1

這對於在腳本被調用後添加的鏈接不起作用。 –

0

是的,ü可以用JS加屬性在HTML命名爲「目標」文件,值爲「_blank」的所有鏈接這個,並寫在JS中的功能,打開新窗口,並設置它的位置爲url;)Google會幫助你。

相關問題