Make HTML anchor to a new window in a strict docktype
We use "target" attribute of the tag to specify the target lo开发者_StackOverflow中文版cation of the link.
But "target" attribute cannot be used in strict doctype (I referred this at http://w3schools.com/tags/tag_a.asp). So what is the solution if we use strict doctype?
In short, JavaScript.
The strict doctype is loosely considered to be "strictly document content" and not behaviour, which the target attribute defines. It assumes the user will decide and have complete control over how links are opened in their browser.
The solution is to use JavaScript to define how links open. You might use a class or other attribute to have a JS library to force them to open in a new window:
<a href="test.php" rel="external">my link</a>
So your script might look like this:
function externalLinks() {
if (!document.getElementsByTagName) return;
var anchors = document.getElementsByTagName("a");
for (var i=0; i<anchors.length; i++) {
var anchor = anchors[i];
if (anchor.getAttribute("href") &&
anchor.getAttribute("rel") == "external")
anchor.target = "_blank";
}
}
window.onload = externalLinks;
This is even easier in jQuery:
$(function(){
$('a[rel=external]').attr('target', '_blank');
});
Either use the transitional doctype, which does allow target
, or if you want to open a new window, use JavaScript.
window.open() is the programmatic way to open a new tab if you cannot rely on the default anchor behavior. However, this will get intercepted by many pop-up blockers. Consider an in-document overlay. http://www.javascript-coder.com/window-popup/unblockable-popup.phtml
精彩评论