核心概念
- Attribute(特性): HTML 标签上的属性
- Property(属性): DOM 对象上的属性
根本区别
| 特性 | Attribute | Property |
|---|---|---|
| 归属 | HTML 标签 | DOM 对象 |
| 值类型 | 总是字符串 | 任意 JS 类型 |
| 大小写 | 不敏感 | 敏感 |
| 操作方式 | getAttribute()/setAttribute() | 点符号操作 |
| 布尔属性 | 存在即为真 | true/false |
操作示例
<input id="myInput" type="text" value="初始值" checked custom-attr="自定义" />
// Attribute 操作
element.getAttribute("value"); // '初始值'
element.setAttribute("value", "新值");
// Property 操作
element.value; // '当前值'
element.value = "新值";
element.checked; // true/false
重要规则
1. 标准属性同步规则
- 初始同步: 页面加载时 property 从 attribute 初始化
- 用户交互后: property 变化,attribute 保持不变
- 程序修改:
- 修改 property → 不影响 attribute
- 修改 attribute → 可能影响 property(取决于时机)
2. value 属性的特殊性
// 特殊行为演示
input.setAttribute("value", "12222"); // 设置attribute
input.getAttribute("value"); // '12222' (attribute)
input.value; // '123' (property - 当前值)
关键点:
- Attribute: 代表 HTML 中设置的默认值
- Property: 代表元素的当前值
- 一旦用户交互,两者"脱钩"
3. 布尔属性处理
<input type="checkbox" checked disabled="disabled" />
// Attribute: 存在即为真
element.getAttribute("checked"); // '' (空字符串,表示存在)
element.getAttribute("disabled"); // 'disabled' (表示存在)
// Property: 真正的布尔值
element.checked; // true/false
element.disabled; // true/false
4. 自定义属性
<div data-id="123" custom-info="hello"></div>
// 非 data-* 属性
element.getAttribute("custom-info"); // 'hello'
element.custom - info; // undefined
// data-* 属性 (推荐使用dataset)
element.dataset.id; // '123'
最佳实践
-
操作当前状态 → 使用 Property
// ✅ 正确 input.value = "新值"; checkbox.checked = true; select.selectedIndex = 0; // ❌ 避免 input.setAttribute("value", "新值"); -
获取初始默认值 → 使用 Attribute
const defaultValue = input.getAttribute("value"); -
操作自定义属性
data-*属性 → 使用dataset- 其他自定义属性 → 使用
getAttribute/setAttribute
-
表单处理始终用 Property
// 获取用户输入 const userInput = input.value; // ✅ const userInput = input.getAttribute("value"); // ❌
记忆口诀
"HTML 写的是 Attribute,JS 用的是 Property;
用户交互看 Property,初始值找 Attribute;
布尔值要用 Property,自定义的用 Attribute。"