javascript - 使用 JavaScript 在之后附加文本一个内的元素
问题描述
目标 - 在文档中的复选框元素之后附加文本
问题 - 目前文本框没有出现在文档中。但是,如果我设置todoLi.appendChild(checkbox)
后它确实会出现,todoLi.textContent = todo.todoText
但这不是我想要的状态。我希望复选框附加.textcontent
在<li>
代码
const todoList = {
todos: [],
addTodo: function(todoText){
this.todos.push({
todoText: todoText,
completed: false
})
}
}
const views = {
displayTodos: function(){
const todosContainer = document.querySelector('#todosContainer')
if(todoList.todos.length === 0){
const message = document.createElement('p')
message.textContent = 'There are currently no todos'
todosContainer.appendChild(message)
}else{
todoList.todos.forEach(function(todo){
const checkbox = document.createElement('input')
const todoLi = document.createElement('li')
checkbox.setAttribute('type', 'checkbox')
todoLi.appendChild(checkbox)
todoLi.textContent = todo.todoText
todosContainer.appendChild(todoLi)
})
}
}
}
views.displayTodos()
<ul id="todosContainer"></ul>
解决方案
const todoList = {
todos: [{
todoText: 'text1'
}]
}
todoList.todos.forEach(function(todo) {
const checkbox = document.createElement('input')
const todoLi = document.createElement('li')
checkbox.setAttribute('type', 'checkbox')
todoLi.appendChild(checkbox);
todoLi.appendChild(document.createTextNode(todo.todoText));
todosContainer.appendChild(todoLi)
})
<ul id="todosContainer"></ul>
推荐阅读
- apache-spark - How to modify a dataframe in-place so that its ArrayType column can't be null (nullable = false and containsNull = false)?
- javascript - 如何在reactjs中将逗号分隔符放在数字类型的输入字段中?
- haskell - Haskell Data.Unique
- javascript - 自动调整多个文本区域的高度以适应加载的内容
- html - 图片元素 - 标题属性
- java - 如何从 Dialog RecyclerView 获取数据到其托管活动?
- c# - 从 DLL 创建 edmx
- javascript - 如何在javascript中同时遍历键和值(反应原生)
- python - 如何查看电报机器人发送消息
- java - Eclipse Maven:SLF4J:类路径包含多个 SLF4J 绑定