待办事项清单和关闭

时间:2020-06-02 14:23:24

标签: javascript list closures scopes

我知道我可以简单地在函数addList中调用函数crossOff。但是,我想知道我的逻辑发生了什么,以及如何正确思考...因此,当我将addList函数存储到变量crossOff2中,然后调用crossOff2时,我认为将调用crossOff函数,因为它已存储在crossOff2中。那么为什么crossOff函数似乎不起作用? 我的另一个问题是,如果将button2.addEventListener('click', addList)替换为button2.addEventListener('click', crossOff2),为什么由于crossOff2调用addList而不能正常工作?

<!DOCTYPE html>
<html>
  <body>
   <h1 id="title">Welcome to the DOM</h1>
    <p>Don't feel <span class="blue">blue</span>, here's what to do.</p>
    <button id="generate-greeting">Hello</button>
    <br/>
    <br/>
    <label for="new-todo">Add a new item to the list:</label>
    <input id="new-todo" type="text">
    <button id="generate-todo">Add to the List!</button>
    <h1>List of things to do</h1>
    <ul class="todos">
    </ul>
<script>
function addList(){
  const containerList = document.querySelector(".todos")
  const list = document.createElement("li")
  const getInput = document.querySelector("#new-todo")
  list.innerText = getInput.value
  containerList.appendChild(list)
  getInput.value = ''
  function crossOff(){
    list.addEventListener('click', function styling(e){
    e.target.style.textDecoration = "line-through";
  })
  }
  return crossOff
}
let crossOff2 = addList()
crossOff2()

const button2 = document.getElementById("generate-todo")
button2.addEventListener('click', addList)

</script>
</body>
</html>

0 个答案:

没有答案