目标 - 在文档中的复选框元素后追加文本
问题 - 目前,文本框不会在文档中出现。然而,它似乎如果我设置todoLi.appendChild(checkbox)
after 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>
只是包装的文字在<span>
并将其添加到innerHTML
.According到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>