实现说明
底层就是函数 addRow。
使用要点
- 浏览器才是这里的运行环境:
document在 Node 里拿不到。
常见问题
「事件委托动态列表」能在裸 Node.js 里跑吗?
不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。
入口签名:function addRow(label)
核心语句
button.dataset.action = row.classList.contains('done') ? 'untoggle' : 'toggle';
代码示例
const list = document.querySelector('#todo-list');
// 一个监听器管所有行:新增行无需重新绑定
list.addEventListener('click', (event) => {
const button = event.target.closest('button[data-action]');
if (!button || !list.contains(button)) return;
const row = button.closest('li');
const action = button.dataset.action;
if (action === 'remove') {
row.remove();
} else if (action === 'toggle') {
row.classList.toggle('done');
button.dataset.action = row.classList.contains('done') ? 'untoggle' : 'toggle';
}
});
// 动态新增的行天然被上面的委托监听覆盖
function addRow(label) {
const li = document.createElement('li');
const text = document.createElement('span');
text.textContent = label;
const toggle = Object.assign(document.createElement('button'), {
textContent: 'toggle',
dataset: { action: 'toggle' },
});
const remove = Object.assign(document.createElement('button'), {
textContent: 'remove',
dataset: { action: 'remove' },
});
li.append(text, toggle, remove);
list.appendChild(li);
}
addRow('delegated row works immediately');