0

我正在为我的课程做一个食谱计算器。我已经到了可以正确验证所有内容并在表格中创建新行的阶段。可悲的是,在配方函数中的 if 语句中,isNaN 总是如此?不管我放什么?谁能帮我这个?

<!DOCTYPE html>
<html>
<head>

<title>Website Title</title>

<script type="text/javascript">
// Declare all variables
var ingredient = document.getElementById("ingredient").value;
var amount = document.getElementById("number").value;
var unit = document.getElementById("unit").value;
var ingredientcount = 0


// The save function
function save(){
var verified = true;
while(verified){
var name = prompt("What's the name of the recipe?")
var serves = prompt("How many people does it serve?")
    if(serves === "" || name === "" || isNaN(serves)=== true)
    {
        alert("You have to enter a name, followed by the number of people it serves. Try again.")
        verified = false;
    }
    else{
        alert("sucess!");
       // array(ingredient,amount,unit,name,serves)
        return;
    }
}

}
// The function to valiate the data and manage everything
function recipe(){
if(ingredient === ""|| amount === "" || unit === "Select Unit"){
  alert("You must fill in all fields.")
}
else if(isNaN(amount)){
    alert("You have to enter a number in the amount field")
}

else{
    alert("hey!")
    alert(recipe[1][2] + recipe[1][1])
    var totalamount = amount + " "+ unit
    insRow(ingredient, totalamount) // post(0,*123456*,"Fish")
    ingredientcount ++;
    alert(ingredientcount);
    }   
}

</script>

</head>

<body>

<h1>Recipe Name</h1>
<h2>Serves many people </h2>
<table border="1" id="table" >

<tr>
<td>
<input type="text" id="ingredient" placeholder="Enter an Ingredient">
</td>
<td>
<input type="text" id="number" placeholder="Enter an amount">
<select id="unit">
        <option>Select Unit</option>
        <option>Grams</option>
        <option>Mililitres</option>
        <option>Number</option>
</select>
</td>
<td>
<button type="button" onclick="recipe()">Add</button>

<button type="button" onclick="save()">Save</button>

</td>
</tr>


<th>Ingredient</th>
<th>Amount</th>
<th> </th>
</table>
</body>
</html>
4

1 回答 1

2

问题是您在页面加载时设置成分、数量和单位的值,而不是在按下“添加”按钮时设置。您需要将这些分配移至 recipe() 函数。

于 2013-09-13T21:22:14.773 回答