我想在使用prompt()请求用户输入之前加载html。只有当我退出提示时才加载html。请看我的代码。
我已尝试在html正文代码的末尾链接javascript,但在提示输入之前仍然没有加载html代码。
这是html代码: -
<!DOCTYPE html>
<html>
<head>
<title>Todo</title>
<script type="text/javascript" src="third.js"></script>
</head>
<body>
<h1>Todo List</h1>
<ul>
<li>new - To add new Todo</li>
<li>list - To list all Todo on Console</li>
<li>quit - To quit the Todo App</li>
<li>delete - To remove an item from Todo App</li>
</ul>
</body>
</html>
这是JavaScript代码: -
var ansa = [];
var ans = prompt("What would you Like to do??");
while(ans !== "quit"){
if(ans === "new"){
addTodo();
} else if (ans === "list") {
listTodo();
} else if (ans === "delete") {
deleteTodo();
};
var ans = prompt("What would you Like to do??");
}
alert("Visit Agaain!!");
function addTodo () {
var newTodo = prompt("Enter a new Todo!!!")
ansa.push(newTodo);
console.log(newTodo + " is added to the Todo")
}
function listTodo () {
// console.log(ansa);
console.log("***********");
ansa.forEach(function (item) {
console.log(ansa.indexOf(item) + ": " + item)
// console.log(index + ": " + item)
})
console.log("***********");
}
function deleteTodo () {
var index = prompt("Which index would like to delete")
ansa.splice(index, 1);
console.log("Todo Item deleted")
}
答案 0 :(得分:3)
即使您在window.onload
回调中运行代码,它也无法正常工作。出于某种原因,这就是浏览器的工作方式。
如果我没错,那么它只能在Internet Explorer上运行。
我在这种情况下一直使用的解决方法是添加一个短暂的超时:
setTimeout(function () {
// your code
}, 200)
答案 1 :(得分:0)
使用setTimeout并添加延迟,请检查以下代码!
var ansa = [];
var delayInMilliseconds = 1000; //1 second
setTimeout(function() {
var ans = prompt("What would you Like to do??");
while(ans !== "quit"){
if(ans === "new"){
addTodo();
} else if (ans === "list") {
listTodo();
} else if (ans === "delete") {
deleteTodo();
};
var ans = prompt("What would you Like to do??");
}
alert("Visit Agaain!!");
}, delayInMilliseconds);
function addTodo () {
var newTodo = prompt("Enter a new Todo!!!")
ansa.push(newTodo);
console.log(newTodo + " is added to the Todo")
}
function listTodo () {
// console.log(ansa);
console.log("***********");
ansa.forEach(function (item) {
console.log(ansa.indexOf(item) + ": " + item)
// console.log(index + ": " + item)
})
console.log("***********");
}
function deleteTodo () {
var index = prompt("Which index would like to delete")
ansa.splice(index, 1);
console.log("Todo Item deleted")
}