将字符串项添加到appendChild li元素

时间:2019-09-13 00:09:41

标签: javascript dom

这是我的代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Todo-List</title>
</head>
<body>
<div id="container">
  <header>
    <h2>To-Do List</h2>
  </header>
  <input id="textArea" type="text" placeholder="Enter list item here!"><input id="submit" type="submit" value="Add">
</div>
<div id="tasks-div">
  <ul id="tasks-list"></ul>
</div>
<script src="script.js"></script>

let textArea = document.getElementById("textArea");
let submit = document.getElementById("submit");
let ul = document.querySelector("ul");
let deleteIcon = document.createTextNode(" X ");

//add todos
let addTodos = submit.addEventListener("click", function() {
let value = textArea.value;
let li = document.createElement("li");
li.textContent = value;
let listItem = ul.appendChild(li);
for (var i = 0; i < listItem.length;i++){
  li += " X ";
}
textArea.value = "";
});

我认为通过使用+ =运算符,它会将X添加到任何li元素中。我该怎么做才能确保在创建li元素时,它的末尾带有“ X”?

1 个答案:

答案 0 :(得分:1)

更改此行

li.textContent = value;

对此

li.innerHTML = `${value} <button>X</button>`;

然后删除该for循环

演示在这里 https://jsfiddle.net/sawyerrken/ze8f5dnu/