所以我试图构建一个to-do-list,当表单提交时,它添加一个li元素,它有一个标签,包含一个输入标签和一个图像标签,但实际上它只添加了li元素,如果有帮助,我们将不胜感激。
const formT = document.querySelector(`[data-new-todo-form]`)
const inputT = document.querySelector(`[data-new-todo-input]`)
const todoList = document.getElementById('todo-list');
const fragment = document.createDocumentFragment();
formT.addEventListener('submit', e => {
e.preventDefault()
let todoName = inputT.value
if(todoName == null || todoName === '') {
return ('enter a Valid text');
} else {
const todo = document.createElement('li')
const todoLabel = document.createElement('label')
const todoInput = document.createElement('input')
const todoImage = document.createElement('img')
todoImage.src = "/images/icon-check.svg";
todoInput.type = 'checkbox'
todoInput.id = 'completed'
todoInput.classList.add('todoInput')
todoLabel.classList.add('todoLabel')
todoLabel.htmlFor = 'completed'
todoLabel.appendChild(todoInput)
todoLabel.appendChild(todoImage)
todo.appendChild(todoLabel)
todo.innerText = todoName
fragment.appendChild(todo)
todoList.appendChild(fragment)
inputT.value = null
}
})
我查了你的密码
todo.innerText = todoName
此行将覆盖您在上面创建的元素。因此,如果您注释掉该行,您将能够检查checkbox元素是否已实际创建。
todoLabel.appendChild(todoInput)
todoLabel.appendChild(todoImage)
const t = document.createTextNode(todoName);
todoLabel.appendChild(t);
因此,不要使用todo.innerText,而是首先使用createTextNode创建文本节点,并将该元素追加到todoLabel元素(或您想要添加的元素)。