我已将 onclick 事件处理程序附加到按钮。单击时,我想显示数据(待办事项列表)。问题是,每次我单击该按钮时,我都会不断调用该函数,将相同的元素添加到 DOM。我在网上找不到真正的解决方案,而且我尝试的任何方法都不起作用。有任何想法吗?谢谢!
ps。我试图只使用 javascript,而不使用 Jquery。
window.onload = init;
function init() {
var button=document.querySelector("#showTodos");
button.onclick = showAll;
}
function showAll () {
var ul = document.getElementById("todoList");
var listFragment = document.createDocumentFragment();
var todos = LocalStorageHelper.read("todos") || [];
todos.map(function(item){
var li = create(item);
listFragment.appendChild(li);
})
ul.appendChild(listFragment);
}
//What I tried (and which doesnt work):
button.onclick = !showAll ? showAll : null;
// Also tried: defining a variable, setting boolean to false and insight the function to true. That doesnt work too, and even if it did, I would need to define a variable as a global variable which I wouldnt want.
var called=false;
button.onclick = !called ? showAll : null;
最佳答案
调用时删除处理程序
window.onload = init;
function init() {
var button=document.querySelector("#showTodos");
button.onclick = showAll;
}
function showAll () {
var ul = document.getElementById("todoList");
var listFragment = document.createDocumentFragment();
var todos = LocalStorageHelper.read("todos") || [];
todos.map(function(item){
var li = create(item);
listFragment.appendChild(li);
})
ul.appendChild(listFragment);
button.onclick = null;
}
关于javascript - 如何仅在单击时触发一次函数调用 - 我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49242977/