Home > Article > Web Front-end > _blank opening a new window does not comply with standards?_CSS/HTML
This article refers to the following articles:
The usual way to open a link in a new window 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.
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:
Open a new windowNow write it like this:
Open a new windowThis is a method that conforms to the strict standard. Of course, it must be combined with a javascript to be effective.
The complete code JS 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 then call it through the external connection method:
That’s it.
Finally, 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".