如果您没有输入要执行的操作,则会收到提醒,但是当关闭它时,会显示要复制的内容。
不确定原因,有人可以解释原因吗?
干杯
https://jsfiddle.net/1usque27/
HTML
<input id="add-to-do" type="text" placeholder="Add to do">
<button id="add-to-do-btn" type="button" name="button">Add</button>
<div id="main"></div>
JS
//要做
var toDo = {
toDos: [],
init: function() {
this.cacheDom();
this.bindEvents();
},
cacheDom: function() {
this.main = document.getElementById('main');
this.addBtn = document.getElementById('add-to-do-btn');
this.toDoValue = document.getElementById('add-to-do')
},
bindEvents: function() {
this.addBtn.addEventListener("click", this.addToDo.bind(this));
},
render: function() {
for(i=0; i<this.toDos.length; i++) {
var toDoList = document.createElement("li");
var toDoListText = document.createTextNode(this.toDos[i]);
toDoList.appendChild(toDoListText);
}
this.main.appendChild(toDoList);
},
addToDo: function() {
var toDoValue = this.toDoValue.value;
if(toDoValue) {
this.toDos.push(this.toDoValue.value);
}
else {
alert("add to do!");
}
this.toDoValue.value = '';
this.render();
}
}
toDo.init();
答案 0 :(得分:4)
因为该功能会在警报后继续执行其余代码。您需要通过返回false来停止执行:
else {
alert("add to do!");
return false;
}
<强> jsFiddle example 强>
答案 1 :(得分:0)
我这样做了https://jsfiddle.net/t0axtoub/
我刚刚将this.toDoValue.value = ''; this.render();
替换为if
。它运作正常。
由于我们没有任何更改,因此我们不需要任何render
答案 2 :(得分:0)
“真实”问题与您的render
方法有关。它始终只渲染最后一项。您可以通过多次手动调用render
来检查此效果。 Demo。您正在重新定义toDoList
内部循环,只有最后一个附加到this.main
。如果您需要重新呈现整个列表,您可以这样做
function() {
var toDoList, toDoListText;
this.main.innerHTML = '' // clean previous render
for(var i=0; i<this.toDos.length; i++) {
toDoList = document.createElement("li");
toDoListText = document.createTextNode(this.toDos[i]);
toDoList.appendChild(toDoListText);
this.main.appendChild(toDoList);
}
}
// To do
var toDo = {
toDos: [],
init: function() {
this.cacheDom();
this.bindEvents();
},
cacheDom: function() {
this.main = document.getElementById('main');
this.addBtn = document.getElementById('add-to-do-btn');
this.toDoValue = document.getElementById('add-to-do')
},
bindEvents: function() {
this.addBtn.addEventListener("click", this.addToDo.bind(this));
},
render: function() {
this.main.innerHTML = ''
for(i=0; i<this.toDos.length; i++) {
var toDoList = document.createElement("li");
var toDoListText = document.createTextNode(this.toDos[i]);
toDoList.appendChild(toDoListText);
this.main.appendChild(toDoList);
}
},
addToDo: function() {
var toDoValue = this.toDoValue.value;
if(toDoValue) {
this.toDos.push(this.toDoValue.value);
}
else {
alert("add to do!");
}
this.toDoValue.value = '';
this.render();
}
}
toDo.init();
<input id="add-to-do" type="text" placeholder="Add to do">
<button id="add-to-do-btn" type="button" name="button">Add</button>
<div id="main"></div>
答案 3 :(得分:0)
只需将渲染插入if(todoValue){ }
addToDo: function() {
var toDoValue = this.toDoValue.value;
if (toDoValue) {
this.toDos.push(this.toDoValue.value);
this.render();
} else {
alert("add to do!");
}
this.toDoValue.value = '';
}