When we want to open a link in a new window, the usual way is to add target="_blank" after the link. There is no problem when we use the transitional DOCTYPE (xh tml1-transitional. dtd), but when we use the strict DOCTYPE (xhtml1- strict.dtd), this method will fail the W3C verification, and the following error message will appear:
"there is no attribute target for this element(in this HTML version)"
It turns out that under the strict DOCTYPE of HTML4.01/XHTML1.0/XHTML1.1, target="_blank", target="_self" and other syntaxes are invalid, and we can only implement them through JavaScript.
A friend asked why target="_blank" is not allowed to be used? This attribute is very convenient. Haha, I don’t know what the W3C experts think. As far as I know, it is mainly about “ease of use and friendliness”, because foreigners think it is impolite to open a new window without the user’s consent or clear prompts. of. Regardless of whether this cancellation is reasonable or not, let’s look at the solution.
rel attribute
HTML4.0 adds a new attribute: rel. This attribute is used to describe the relationship between the link and the page containing the link, as well as the target of the link. rel has many attribute values, such as next, previous, chapter, section, etc. What we want to use is the rel="externa l" attribute. The original code was written like this:
<a href="document.html" target="_blank"> Open a new window</a>
Now it will be written like this:
<a href="document.html" rel="external">Open a new window</a>
This is a strict method. Of course, it must be combined with a javascript to be effective.
The complete code JS of javascript is as follows:
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;
You can save it as a .js file (such as external.js) and call it through the external connection method:
<script type="text/javascript" src="external.js"></script>
That's it.
Finally, I would like to add that the target="new" used by my website is allowed under the transitional DOCTYPE, but it does not meet the strict standard. I will use strict mode in the next revision and change all target="new" to rel="external".