html 标准属性不要用 setAttribute 方法

html 中有些属性,譬如 checked , autofocus 只要存在就会有效,即使值是 false ,譬如:

<input autofocus=false id='test'>
<input type="checkbox" checked=false id="test2">

结果:

image

如果要取消这种行为,使用 setAttribute 设置假值是无效的,因为文档也说了,只要属性存在就有效:

test.setAttribute('autofocus', false)
test2.setAttribute('checked', false)

结果:

image

所以要取消,首选:

test.autofocus = false
test2.checked = false

如图:

image

image

或者直接移除属性:

test.removeAttribute('autofocus')
test2.removeAttribute('checked')

image

这种方式为什么会生效呢?因为

调用 removeAttribute() 这个方法不仅会清除特性的值,而且也会从元素中完全删除特性

实际上,如果要添加这些属性,很明显也有两种方式:

首选

test.autofocus = true
test2.checked = true

image

或者:

test.setAttribute('autofocus', true)
test2.setAttribute('checked', true)

结果:

image

如果你仔细观察,上面两种操作方案,浏览器的渲染结果是不一样的;

为什么推荐第一种呢?首先, autofocus 和 checked 属性都是标准规定的属性,所以可以通过元素属性直接访问,setAttribute 等方法更多的可以用来操作自定义属性,如 data- 开头的属性,如果对于标准规定的属性用 setAttribute 等方法,会出现些异常情况,譬如:

下面操作是无效的

test.setAttribute('autofocus', false)
test2.setAttribute('checked', false)

而且,会导致下面的结果跟看起来的有分歧

console.log(test.autofocus, test2.checked);//true,true

测试浏览器:

image

参考文档:

JavaScript高级程序设计-第3版-中

原文地址:https://www.cnblogs.com/xianshenglu/p/8884511.html