Is it correct to use single quotes for HTML attributes?

前端 未结 15 2555
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 05:57

Recently I\'ve been seeing a lot of this:


    

        
相关标签:
15条回答
  • 2020-12-01 06:27

    Single quotes are perfectly legal in (X)HTML. Using a backslash to escape them, on the other hand, isn't. <img src='http://widget-site-example.com/ross.jpg' alt='Ross\'s Widget' /> is an image with the alt text "Ross\", and empty s and Widget/Widget' attributes. The correct way of escaping an apostrophe in HTML is &#39;.

    0 讨论(0)
  • 2020-12-01 06:29

    It's easier when you want to embed double quotes.

    0 讨论(0)
  • 2020-12-01 06:30

    You should avoid quotes altogether.

    In your example only one quoted attribute actually needed quotes.

    <!-- best form -->
    <a href=http://widget-site-example.com/example.html>
      <img src=http://widget-site-example.com/ross.jpg alt='Ross&#39;s Widget' />
    </a>
    

    If you do use quotes, there is no hard and fast rule, but I've seen most commonly single quotes, with double quotes on the inside if necessary.

    Using double quotes won't pass some validators.

    0 讨论(0)
  • 2020-12-01 06:35

    I know this is an old thread, but still very much relevant.

    If you want control over quotes in your generated HTML, you can use the sprintf() function in PHP (and similar calls available in many other languages):

    $html = sprintf('<a href="%s">%s</a>', $url, $text);
    

    Using sprintf() allows the format string to be easily modifiable by retrieving it from a database or configuration file, or via translation mechanisms.

    It is very readable, and allows either double or single quotes in the generated HTML, with very little change and never any escaping:

    $html = sprintf("<a href='%s'>%s</a>", $url, $text);
    
    0 讨论(0)
  • 2020-12-01 06:35

    Why not save pressing the SHIFT Key. One less keystroke for the same milage.

    0 讨论(0)
  • 2020-12-01 06:37

    Another case where you may want to use single quotes: Storing JSON data in data attributes:

    <tr data-info='{"test":true}'></tr>
    

    JSON object keys must be in double quotes, so the attribute itself cannot.

    0 讨论(0)
提交回复
热议问题