继承人HTML:
<!doctype html>
<head>
<title>Food Saver</title>
<script src="mycode.js"></script>
</head>
<body>
<form>
<input type="text" id="foodInput" placeholder="Enter food">
<input type="button" id="addFood" value="Add Food">
</form>
<ul id="foodList">
</ul>
</body>
</html>
以及与之相关的JavaScript:
window.onload=init;
function init(){
var addFoodButton = getElementById("addFood");
addFoodButton.onclick = handleAddFoodButtonClick;
}
function handleAddFoodButtonClick(){
var textInput=getElementById("foodInput");
var food = textInput.value;
if(food===""){
alert("Please enter a food");
}
else{
var li = document.createElement("li");
li.innerHTML=food;
var ul = getElementById("foodList");
ul.appendChild(li);
}
}
为什么当我尝试提交食物值或空字符串时没有任何反应,我的代码中的错误是什么
答案 0 :(得分:3)
getElementById应该是document.getElementById:
window.onload=init;
function init(){
var addFoodButton = document.getElementById("addFood");
addFoodButton.onclick = handleAddFoodButtonClick;
}
function handleAddFoodButtonClick(){
var textInput = document.getElementById("foodInput");
var food = textInput.value;
if(food===""){
alert("Please enter a food");
}
else{
var li = document.createElement("li");
li.innerHTML=food;
var ul = document.getElementById("foodList");
ul.appendChild(li);
}
}
答案 1 :(得分:0)
试试这个
window.onload=init;
function init(){
var addFoodButton = document.getElementById("addFood");
addFoodButton.onclick = handleAddFoodButtonClick;
}
function handleAddFoodButtonClick(){
var textInput=getElementById("foodInput");
var food = textInput.value;
if(food===""){
alert("Please enter a food");
}
else{
var li = document.createElement("li");
li.innerHTML=food;
var ul = document.getElementById("foodList");
ul.appendChild(li);
}
}
答案 2 :(得分:0)
每当你没有看到什么问题时,最好将你的代码抛入JSLint,继续点击JSLint按钮,直到它没有给你任何错误(或者你决定忽略或禁用某些警告)
它可以在很短的时间内教你很多。我刚刚这样做了,并提出了JSLint的建议。
function handleAddFoodButtonClick() {
'use strict';
var food = document.getElementById('foodInput').value;
// if variable is false, zero, null, undefined, empty string or NaN, it's false
if (!food) {
alert('Please enter a food');
} else {
var li = document.createElement('li');
li.innerHTML = food;
document.getElementById('foodList').appendChild(li);
}
}
function init() {
'use strict';
var addFoodButton = document.getElementById('addFood');
addFoodButton.onclick = handleAddFoodButtonClick;
}
window.onload = init;
您也可以将代码粘贴到JSHint,事实上,使用您的原始代码会产生3个错误:
One undefined variable
3 getElementById
7 getElementById
16 getElementById