目标-在文档中复选框元素之后添加文本
问题-当前文本框未出现在文档中。但是,如果我在todoLi.appendChild(checkbox)
之后设置todoLi.textContent = todo.todoText
,它确实会出现,但这不是我想要的状态。我希望复选框附加到.textcontent
的{{1}}
代码
<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()
答案 0 :(得分:2)
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>
答案 1 :(得分:1)
只需将文本包装在<span>
中并将其添加到innerHTML
中即可。根据 MDN
在节点上设置textContent 删除该节点的所有子节点,并将其替换为具有给定字符串值的单个文本节点
在此处查看文档 Node.textContent
const checkbox = document.createElement('input')
const todoLi = document.createElement('li')
const todosContainer = document.querySelector('#todosContainer');
checkbox.setAttribute('type', 'checkbox')
let text = "some text"
todoLi.appendChild(checkbox)
todoLi.innerHTML += `<span>${text}</span>`;
todosContainer.appendChild(todoLi)
<ul id="todosContainer"></ul>