Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k views
in Technique[技术] by (71.8m points)

I am trying to make a todo list in javascript but the HTML doesn't show it

I'm trying to code a todo list in javascript, but somehow it doesn't work.

this is my JavaScript and HTML:

let todos = [] 
function createTodo() {
    let newTodo = {
        text: '',
        checked: 0
    }
    newTodo['text'] = prompt('Item description')
    todos.push(newTodo)
    
}

for (i in todos) {
    let listItem = document.createElement('li')
    let itemText = document.createTextNode(i['text'])
    console.log('itemText: ' + itemText)
    listItem.appendChild(itemText)
    console.log('listItem: ' + listItem)
    document.getElementById('todo-list').appendChild(listItem)
}
<!DOCTYPE html>
<html>
  <head>
    <title>TODO App</title>
    <link rel="stylesheet" type="text/css" href="./styles.css" />
  </head>
  <body>
    <div class="container center">
      <h1 class="center title">My TODO App</h1>
      <div class="flow-right controls">
        <span>Item count: <span id="item-count">0</span></span>
        <span>Unchecked count: <span id="unchecked-count">0</span></span>
      </div>
      <button class="button center" onClick="createTodo();">New TODO</button>
      <ul id="todo-list" class="todo-list">
      </ul>
    </div>
    <script src="./script.js"></script>
  </body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As I can see in your code, there is nowhere to add created elements to HTML. And when it comes to open prompt, you should get value from the input.

This is how to get input value and reflects it to the HTML

let todos = []
function createTodo() {
    let newTodo = {
        text: '',
        checked: 0
    }
    newTodo['text'] = prompt('Item description')
    if( newTodo.text != null ) {
        todos.push(newTodo)
        reflectToHtml(newTodo)
    }
}
function reflectToHtml(i) {
    let listItem = document.createElement('li')
    let itemText = document.createTextNode(i['text'])
    listItem.appendChild(itemText)
    document.getElementById('todo-list').appendChild(listItem)
    document.getElementById('item-count').innerText = todos.length
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...