gpt4 book ai didi

Javascript 食谱计算器,卡在 isNan() 函数上?

转载 作者:行者123 更新时间:2023-12-02 18:21:22 24 4
gpt4 key购买 nike

我正在为我的类(class)制作一个食谱计算器。我已经达到了它将正确验证所有内容并在表中创建新行的阶段。遗憾的是,在配方函数中的 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>

最佳答案

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

关于Javascript 食谱计算器,卡在 isNan() 函数上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18795304/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com