javascript addEventlistener“点击”不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33906015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript addEventlistener "click" not working
提问by Jason Woo
I am working on making a To-Do list as a Chrome new tab extension.
我正在制作一个待办事项列表作为 Chrome 新标签扩展。
My html file:
我的 html 文件:
<head>
</head>
<body>
<h2 id="toc-final">To Do List</h2>
<ul id="todoItems"></ul>
<input type="text" id="todo" name="todo" placeholder="What do you need to do?" style="width: 200px;">
<button id="newitem" value="Add Todo Item">Add</button>
<script type="text/javascript" src="indexdb.js"></script>
</body>
</html>
Previously the button element was an input type with onClick(), but Chrome does not allow that. So I had to make a javascript function that will fire when it's clikced. In my indexdb.js:
以前按钮元素是带有 onClick() 的输入类型,但 Chrome 不允许这样做。所以我必须制作一个 javascript 函数,当它被点击时会触发。在我的 indexdb.js 中:
var woosToDo = {};
window.indexedDB = window.indexedDB || window.webkitIndexedDB ||
window.mozIndexedDB;
woosToDo.indexedDB = {};
woosToDo.indexedDB.db = null;
window.addEventListener("DOMContentLoaded", init, false);
window.addEventListener('DOMContentLoaded', function () {
document.getElementById("newitem").addEventListener("click", addTodo(), false);
});
...
...
function addTodo() {
var todo = document.getElementById("todo");
woosToDo.indexedDB.addTodo(todo.value);
todo.value = "";
}
Why is nothing happening when I click the button w/ id="newitem" ?
为什么当我单击带有 id="newitem" 的按钮时什么也没有发生?
回答by TbWill4321
When attaching the function, you are executing it first, and attaching the return value undefined
to the event. Remove the parenthesis:
附加函数时,您首先执行它,并将返回值附加undefined
到事件。去掉括号:
.addEventListener("click", addTodo, false);
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.
当您将其addTodo()
作为参数放置时,您并没有传递函数本身。它做的第一件事是执行函数并使用返回值作为参数。
Since functions without a return
statement implicitly result in undefined
, the original code was actually running the function, and then attaching this:
由于没有return
语句的函数隐式导致undefined
,原始代码实际上是在运行该函数,然后附加以下内容:
.addEventListener("click", undefined, false);
回答by Moin
Instead of two DOMContentLoaded
listeners, try one.
DOMContentLoaded
尝试一个,而不是两个听众。
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);
});