html – 设置false值与删除属性

我正在读一些关于布尔属性 here内容,它表示对于布尔属性(在此特定示例中,< audio>的循环属性),无论您设置什么值,它都将被识别为“true”.为了真正设置为falsy,你不能将它设置为loop = false或使用javascript作为[‘loop’] = false,但必须删除属性,例如通过执行removeAttribute(‘loop’).这是真的?

我首先相信它,但就Chrome检查它,似乎设置为[‘loop’] = false实际上会让它被识别为假的.我不确定这个事实在跨浏览时是多么强大.浏览器之间有什么区别吗?

解决方法

布尔属性在这里解释:

http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.3.4.2

Some attributes play the role of boolean variables (e.g.,the selected
attribute for the OPTION element). Their appearance in the start tag
of an element implies that the value of the attribute is “true”. Their
absence implies a value of “false”.

Boolean attributes may legally take a single value: the name of the
attribute itself (e.g.,selected=”selected”).

因此,虽然某些浏览器可能会将字符串“false”解释为未设置该值,但其他浏览器可能无法决定(这是正确的行为).实际上,据我所知(或者想到),任何非空字符串通常都会将值设置为on / true(不管规范所说的是合法值).我相信这也是未定义的行为,所以这可能会改变或者在浏览器与浏览器之间有所不同(不要依赖它).

最重要的是,仅仅因为浏览器或两个浏览器可能偏离规范并不意味着你应该这样做.完全删除属性是要走的路.

附录:仔细观察你的评论和问题,我认为你可能会对属性值感到困惑.在HTML中,attr = false和attr =“false”完全相同.任何版本的HTML都不需要引号(除非在值包含空格时需要删除歧义).例如:

<input class=required>
<!-- This is fine -->

<input class=title required>
<!-- this is fine too,but "required" will be parsed as an attribute -->

<input class="title required">
<!-- To have two classes,we need the quotes -->

所有属性值(在具有它们的元素上)都被视为字符串.换句话说,在HTML中没有像javascript那样的真正的布尔值(或NULL值).

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些