首页 > 解决方案 > 使用 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>

    标签: javascripthtmldom

    解决方案


    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>


    推荐阅读