javascript addEventlistener “click” not working

别说谁变了你拦得住时间么 提交于 2019-12-05 08:50:17

When attaching the function, you are executing it first, and attaching the return value undefined to the event. Remove the parenthesis:

.addEventListener("click", addTodo, false);

Edit: Explaination.

When you put addTodo() as a parameter, you are not passing the function itself. The first thing it does is execute the function and use the return value as the parameter instead.

Since functions without a return statement implicitly result in undefined, the original code was actually running the function, and then attaching this:

.addEventListener("click", undefined, false);

Instead of two DOMContentLoaded listeners, try one.

Change this:

window.addEventListener("DOMContentLoaded", init, false);

    window.addEventListener('DOMContentLoaded', function () {
      document.getElementById("newitem").addEventListener("click", addTodo(), false);
    });

To this:

window.addEventListener('DOMContentLoaded', function () {
  init();
  document.getElementById("newitem").addEventListener("click", addTodo, false);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!