Create a W3C validated anchor link with target=“_b

2019-02-12 15:58发布

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

<a href="/path/to/site" target="_blank">glide by the people</a>

Problem is that it does not pass the W3C validator. How do I create a link like the above that does validate?

标签: css xhtml target
11条回答
Evening l夕情丶
2楼-- · 2019-02-12 16:55

Assuming strict XHTML, you would bind an onclick event to the anchor in question. Something like:

<a href="/path/to/my/link" onclick="window.open('/path/to/my/link');return false;">My link</a>

One would also argue that you should be binding that onclick action separately with external JavaScript due to progressive enhancement and separating behavior from your markup, but that's the basic way to go about it.

查看更多
小情绪 Triste *
3楼-- · 2019-02-12 16:57
  1. Validation isn't the be all and end all of coding quality.

  2. Some things are "standard" in browsers without being a w3c standard.

  3. Using a bit of JS is a little overkill when the function already exists.

查看更多
别忘想泡老子
4楼-- · 2019-02-12 16:57
  1. Add rel="new-window" attribute to the link (instead of target="_blank")
  2. add jquery script to head of page and add the following snippet

    <script type="text/javascript">
        $(document).ready(function(){
            $('a[rel="new-window"]').click(function(){
                window.open(this.href);
            })
        });
    </script>
    

(Please note that as I typed this in the stackoverflow textbox, I haven't tested it.)

查看更多
▲ chillily
5楼-- · 2019-02-12 16:57

Actually, the proposed here solutions with adding the "target" attribute through JavaScript are completely standards compliant!

The thing is that according to the W3C DOM Level 1 specification the interface HTMLLinkElement DO have target attribute, although the A element from HTML 4.01 specification do not have it.

So it's invalid to write "target" attribute in html file, but is valid to add it to the document tree later via DOM interfaces using JS.

查看更多
萌系小妹纸
6楼-- · 2019-02-12 16:58

Use this doctype:

<!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhmtl1/DTD/xhmtl1-transitional.dtd"> 

1.0 transitional accommodates some html "legacy" code, including target="_blank".

查看更多
登录 后发表回答