Create a W3C validated anchor link with target=“_blank”

前端 未结 11 1874
臣服心动
臣服心动 2021-01-04 22:51

I have the following piece of HTML that creates a new window when clicked:

glide by the people
         


        
11条回答
  •  无人及你
    2021-01-04 23:25

    I think you're asking the wrong question. The target attribute is not valid in strict XHTML 1.0 no matter whether you insert it with JavaScript or just have it in the server response.

    If you really want that attribute, you have to use a different doctype, but that's not really the right answer either.

    You should ask yourself why you want the attribute. I'm guessing you're trying to create a new tab or window. Needless to say this is generally considered bad design (it takes control away from the user), but if you really want to do it, you could do it with JavaScript.

    Here's how:

    Keep your links but add a special class, e.g. "popup" to them. Then add a line of JavaScript (preferably using a framework like jQuery or Prototype to make it easier) that takes all links with that class and gives them an on-click handler that results in the creation of a new tab/window and cancels the default action (i.e. stops the link from working as a link). That will still annoy people as it overrides the expected behaviour, though.

    What you should not do is replace the links with dummy links and rely on JavaScript for the links to work.

    Disregard that. The target attribute is no longer deprecated in HTML (the living standard or "5", depending on whether you follow WHAT WG or the W3C). The correct answer today is to just replace your DOCTYPE with this:

    
    

    Note that it no longer has to be uppercase nor actually look like a full SGML DOCTYPE declaration. It's just a vestigial artefact identifying the document as standards compliant HTML.

提交回复
热议问题