实现说明
顶层就这几处状态:input、box。
使用要点
- 这是浏览器侧代码——
document在 Node 里解析不到。 - 演示输出是带标签的(
property picks up attribute:、attribute unchanged:、property now:),每个操作都会留下自己的一行标注。
常见问题
「attribute 与 property 各自为政」能在裸 Node.js 里跑吗?
不能——document 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。
核心语句
input.setAttribute('value', 'typed in markup');
const input = document.createElement('input');
const box = document.createElement('input');
代码示例
// attribute 写在 HTML 标记上(字符串);property 是 DOM 对象上的 JS 值
const input = document.createElement('input');
input.setAttribute('value', 'typed in markup');
console.log('property picks up attribute:', input.value);
// 用户或代码改过 property 之后:两者从此各自独立
input.value = 'typed by user';
console.log('attribute unchanged:', input.getAttribute('value'));
console.log('property now:', input.value);
// checked 同理:attribute 是初始默认值,property 是当前状态
const box = document.createElement('input');
box.type = 'checkbox';
box.setAttribute('checked', '');
console.log('defaultChecked:', box.defaultChecked, '| checked:', box.checked);
box.checked = false;
console.log('after uncheck:', box.defaultChecked, box.checked, '| attr present:', box.hasAttribute('checked'));