Is it correct to use single quotes for HTML attrib

2019-01-10 21:38发布

Recently I've been seeing a lot of this:

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

Is it valid to use single quotes in HTML? As I've highlighted above it's also problematic because you have to escape apostrophes.

15条回答
forever°为你锁心
2楼-- · 2019-01-10 22:16

When using PHP to generate HTML it can be easier to do something like:

$html = "<img src='$url' />";

than concatenating a string with a variable with a string, as PHP parses variables in double-quoted strings.

查看更多
叼着烟拽天下
3楼-- · 2019-01-10 22:16

Single quotes generate a cleaner page with less clutter. You shouldn't be escaping them in HTML strings and it's your choice which to use... my preference is single quotes normally and if I need to include a single quote in the string (e.g. as delimiters for a string inside the string), I use double quotes for one & single for the other.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-10 22:18

In PHP, echo takes multiples parameters. So, if one would like to omit the concatenation operator, they could done something like and still use double quotes :

echo '<input type="text" value="', $data, '" />';
查看更多
家丑人穷心不美
5楼-- · 2019-01-10 22:20

I find using single quotes is handy when dynamically generating HTML using a programming language that uses double quote string literals.

e.g.

String.Format("<a href='{0}'>{1}</a>", Url, Desc)
查看更多
唯我独甜
6楼-- · 2019-01-10 22:20

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.

查看更多
虎瘦雄心在
7楼-- · 2019-01-10 22:23

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

查看更多
登录 后发表回答