JS课程待办应用开发问题:脚本创建元素未在浏览器显示文本
问题修复方案
你代码中存在两处错误,修改后即可正常渲染对应文本:
- 属性名拼写错误:创建统计标题h2时,你将
textContent错写为textContext,导致统计文本无法成功赋值到元素上 - 赋值逻辑错误:循环创建待办项p标签时,你错误赋值了固定字符串
'todo.text',且待办对象的存储字段为title而非text,需要正确读取每个循环项的title属性
修复后完整JS代码
const todos = [{ title: 'make bed', completed: true }, { title: 'shower', completed: false }, { title: 'shave', completed: true }, { title: 'feed the cat', completed: false }, { title: 'crush the day', completed: false }] const incompleteTodos = todos.filter(function (todo) { return !todo.completed }) const summary = document.createElement('h2') // 修正拼写错误 summary.textContent = `You have ${incompleteTodos.length} todos left` document.querySelector('body').appendChild(summary) todos.forEach(function (todo) { const p = document.createElement('p') // 修正赋值逻辑,读取todo的title属性 p.textContent = todo.title document.querySelector('body').appendChild(p) })
浏览器运行效果

内容的提问来源于stack exchange,提问作者LittleSister
相关产品推荐
相关产品推荐

