HTML 中是否允许使用单引号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/273354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:42:10  来源:igfitidea点击:

Are single quotes allowed in HTML?

html

提问by Greg Hewgill

I am a big time user of using double quotes in PHP so that I can interpolate variables rather than concatenating strings. As a result, when I am generating HTML I often use single quotes for setting tag fields. For example:

我很喜欢在 PHP 中使用双引号,这样我就可以插入变量而不是连接字符串。因此,当我生成 HTML 时,我经常使用单引号来设置标签字段。例如:

$html = "<input type='text' name='address' value='$address'>";

Now this is far more readable to me than either

现在这对我来说比任何一个都更具可读性

$html = "<input type=\"text\" name=\"address\" value=\"$address\">";

or

或者

$html = '<input type="text" name="address" values="' . $address . '">' ;

From brief searches I have heard people saying that single quotes for HTML fields is not recognized by EVERY browser. Thus I am wondering what browsers would have problems recognizing single quote HTML?

从简短的搜索中,我听到人们说 HTML 字段的单引号不能被每个浏览器识别。因此,我想知道哪些浏览器在识别单引号 HTML 时会遇到问题?

回答by Greg Hewgill

This is similar to When did single quotes in HTML become so popular?. Single quotes around attributes in HTML are and always have been permitted by the specification. I don't think any browsers wouldn't understand them.

这类似于HTML 中的单引号何时变得如此流行?. HTML 中的属性周围的单引号一直是规范允许。我认为任何浏览器都不会理解它们。

回答by Adam Bellaire

As noted by PhiLho, although there is a widely spread belief that single quotes are not allowed for attribute values, that belief is wrong.

正如 PhiLho 所指出的那样,尽管人们普遍认为属性值不允许使用单引号,但这种看法是错误的。

The XML standardpermits both single and double quotes around attribute values.

XML标准允许各地属性值单引号和双引号。

The XHTML standard doesn't say anything to change this, but a related section which states that attribute values must be quoteduses double quotes in the example, which has probably lead to this confusion. This example is merely pointing out that attribute values in XHTML must meet the minimum standard for attribute values in XML, which means they must be quoted (as opposed to plain HTML which doesn't care), but does not restrict you to either single or double quotes.

XHTML 标准没有说明要改变这一点,但是在示例中,声明属性值必须被引用的相关部分使用了双引号,这可能会导致这种混淆。这个例子只是指出 XHTML 中的属性值必须满足 XML 中属性值的最低标准,这意味着它们必须被引用(与不关心的纯 HTML 相对),但不限制您使用单个或双引号。

Of course, it's always possible that you'll encounter a parser which isn't standards-compliant, but when that happens all bets are off anyway. So it's best to just stick to what the specification says. That's why we have specifications, after all.

当然,您总是有可能遇到不符合标准的解析器,但是当发生这种情况时,无论如何都不会下注。所以最好只遵守规范所说的。毕竟,这就是我们制定规范的原因。

回答by FlySwat

I have heard people saying that single quotes for HTML fields is not recognized by EVERY browser

我听说有人说 HTML 字段的单引号不能被每个浏览器识别

That person is wrong.

那个人错了。

回答by PhiLho

Don't believe everything you see on Internet...
Funnily, I just answered something similar to somebody declaring single quotes are not valid in XHTML...

不要相信你在互联网上看到的一切......
有趣的是,我刚刚回答了一些类似于某人声明单引号在 XHTML 中无效的问题......

Mmm, I look above while typing, and see that Adam N propagates the same belief. If he can back up his affirmation, I retract what I wrote... AFAIK, XML is agnostic and accepts both kinds of quote. I even tried and validated without problem an XHTML page with only single quotes.

嗯,我在打字的时候往上看,看到 Adam N 传播了同样的信念。如果他能支持他的肯定,我撤回我写的东西...... AFAIK,XML 是不可知的,并接受两种引用。我什至尝试并验证了一个只有单引号的 XHTML 页面没有问题。

回答by inteblio

Only problem is data going into TEXT INPUT fields. Consider

唯一的问题是数据进入文本输入字段。考虑

<input value='it's gonna break'/>

Same with:

同:

<input value="i say - "this is gonna be trouble" "/>

You can't escape that, you have to use htmlspecialchars.

你无法逃避,你必须使用htmlspecialchars.

回答by connexo

As I was looking to find information on this in a much more recent version of the specificationand it took me quite some time to find it, here it is:

由于我希望在最新版本的规范中找到有关此的信息,我花了很长时间才找到它,这里是:

From

HTML 5.3

Editor's Draft, 18 October 2018

[...]

8.1.2.3. Attributes

Single-quoted attribute value syntax

The attribute name, followed by zero or more space characters, followed by a single U+003D EQUALS SIGN character, followed by zero or more space characters, followed by a single U+0027 APOSTROPHE character ('), followed by the attribute value, which, in addition to the requirements given above for attribute values, must not contain any literal U+0027 APOSTROPHE characters ('), and finally followed by a second single U+0027 APOSTROPHE character (').

In the following example, the type attribute is given with the single-quoted attribute value syntax:

<input type='checkbox'>

If an attribute using the single-quoted attribute syntax is to be followed by another attribute, then there must be a space character separating the two.

http://w3c.github.io/html/single-page.html#elements-attributes

HTML 5.3

编辑草稿,2018 年 10 月 18 日

[...]

8.1.2.3. 属性

单引号属性值语法

属性名称,后跟零个或多个空格字符,后跟单个 U+003D EQUALS SIGN 字符,后跟零个或多个空格字符,后跟单个 U+0027 撇号字符 ('),后跟属性值,除了上面对属性值给出的要求之外,其中不得包含任何文字 U+0027 撇号字符 ('),最后不得包含第二个单个 U+0027 撇号字符 (')。

在以下示例中,type 属性使用单引号属性值语法给出:

<input type='checkbox'>

如果使用单引号属性语法的属性后跟另一个属性,则必须有一个空格字符将两者分开。

http://w3c.github.io/html/single-page.html#elements-attributes

回答by rchacko

I used single quotes in HTML pages and embedded JavaScripts into it and its works fine. Tested in IE9, Chrome and Firefox - seems working fine.

我在 HTML 页面中使用了单引号并将 JavaScript 嵌入其中,并且效果很好。在 IE9、Chrome 和 Firefox 中测试 - 似乎工作正常。

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
        <title>Bethanie Inc. data : geographically linked</title>
        <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'></script>
        <script src='https://maps.googleapis.com/maps/api/js?v=3.11&sensor=false' type='text/javascript'></script>
        <script type='text/javascript'> 
        // check DOM Ready
        $(document).ready(function() {
            // execute
            (function() {
                /////////////// Addresses ///////////////////
                var locations = new Array();
                var i = 0;
                locations[i++] = 'L,Riversea: Comp Site1 at Riversea,1 Wallace Lane Mosman Park WA 6012'
                locations[i++] = 'L,Wearne: Comp Site2 at Wearne,1 Gibney St Cottesloe WA 6011'
                locations[i++] = 'L,Beachside:Comp Site3 Beachside,629 Two Rocks Rd Yanchep WA 6035'

                /////// Addresses/////////
                var total_locations = i;
                i = 0;
                console.log('About to look up ' + total_locations + ' locations');
                // map options
                var options = {
                    zoom: 10,
                    center: new google.maps.LatLng(-31.982484, 115.789329),//Bethanie  
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    mapTypeControl: true
                };
                // init map
                console.log('Initialise map...');
                var map = new google.maps.Map(document.getElementById('map_canvas'), options);
               // use the Google API to translate addresses to GPS coordinates 
               //(See Limits: https://developers.google.com/maps/documentation/geocoding/#Limits)
                var geocoder = new google.maps.Geocoder();
                if (geocoder) {
                    console.log('Got a new instance of Google Geocoder object');
                    // Call function 'createNextMarker' every second
                    var myVar = window.setInterval(function(){createNextMarker()}, 700);
                    function createNextMarker() {
                        if (i < locations.length) 
                       {
                            var customer = locations[i];
                            var parts = customer.split(','); // split line into parts (fields)
                            var type= parts.splice(0,1);    // type from location line (remove)
                            var name = parts.splice(0,1);    // name from location line(remove)
                            var address =parts.join(',');   // combine remaining parts
                            console.log('Looking up ' + name + ' at address ' + address);
                            geocoder.geocode({ 'address': address }, makeCallback(name, type));
                            i++; // next location in list
                            updateProgressBar(i / total_locations);


                        } else 
                       {
                            console.log('Ready looking up ' + i + ' addresses');
                            window.clearInterval(myVar);
                        }
                    }

                    function makeCallback(name,type) 
                   {
                        var geocodeCallBack = function (results, status) {
                            if (status == google.maps.GeocoderStatus.OK) {
                                var longitude = results[0].geometry.location.lng();
                                var latitude = results[0].geometry.location.lat();
                                console.log('Received result: lat:' + latitude + ' long:' + longitude);
                                var marker = new google.maps.Marker({
                                    position: new google.maps.LatLng(latitude, longitude),
                                    map: map,
                                    title: name + ' : ' + '\r\n' + results[0].formatted_address});// this is display in tool tip/ icon color
                                   if (type=='E')  {marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')};

回答by UnkwnTech

I also tend to use single quotes in HTML and I have never experienced a problem.

我也倾向于在 HTML 中使用单引号,而且我从未遇到过问题。

回答by Gena Moroz

Recently i've experienced a problem with Google Search optimization. If has a single quotes, it doesn't seem to crawl linked pages.

最近,我遇到了 Google 搜索优化问题。如果有单引号,它似乎不会抓取链接的页面。

回答by mcandre

... or just use heredocs. Then you don't need to worry about escaping anything but END.

...或者只是使用heredocs。然后你不需要担心逃避任何东西,除了END.