在HTML5标签中,存在很多属性是没有属性值的,我们使用的时候直接输入属性名称就能够使用了。比如:

selected
checked
async
required
multiple
disabled

它们都是布尔属性,也就是它们不需要设置属性值,我们在html5的标签里面是直接输入名称使用的:

  <button disabled>click</button>

但是如果我们使用形如下面的方式来使用的话,虽然功能可以实现,但是其实会报警告,甚至eslint会报错:

  <button disabled='true'>click</button>

也就是说,如果我们使用常规的加true的模式来使用这种布尔属性的话,其实是不符合html5的规范的。

根据stack overflow中的描述,我们找到了答案:

2.5.2 Boolean attributes

  A number of attributes are boolean attributes. The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

  If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

  The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.

  *Note that this means that <div hidden="true"> is not allowed in HTML5.
  Correct would be either <div hidden> or <div hidden=""> or <div hidden="hidden"> or case-insensitive and single quotes/unquoted variations of any of them.*

总结起来,也就是说:我们在html5标签中使用布尔属性可以使用如下几种形式:

  <button disabled>click</button>    //推荐这种
  <button disabled="">click</button>
  <button disabled="disabled">click</button>    //推荐这种
  <button disabled="任意字符串">click</button>

所以我们在使用js动态添加布尔属性的时候,应该使用setAttribute(‘async’,’async’)这种形式是最靠谱的。