我正在尝试为食谱卡编写JavaScript。我认为最好使用对象构造函数,因为我要使用相同的条件创建多个配方。我需要使用一个数组作为成分,但似乎无法使它起作用。唯一会显示的是配方名称,然后数组返回未定义状态。
我对JS非常陌生,所以请像小孩子一样对我分解一下,同时也要友善:)
我也很抱歉代码是用这种方式编写的。我正在使用移动应用程序,因此无法像往常一样在特定的框中将其写入。如果愿意,可以使用CodePen:https://codepen.io/Nikofem/pen/RwwgGog
这是HTML代码:
<div class="recipe-card">
<aside>
<img src="https://divascancook.com/wp-content/uploads/2015/01/no-bake-engery-bites-peanut-butter-chocolate-healthy-granola-snack-recipe-2.jpg" alt="Granola Engergy Bites" />
</aside>
<article>
<h2 id="name1"></h2>
<h4 id="ingredients1"></h4>
<ul>
<li><span class="icon icon-users"></span><span>10 - 15</span></li>
<li><span class="icon icon-clock"></span><span>15 min</span></li>
</ul>
</article>
</div>
这是我到目前为止拥有的JS代码:
function Recipe(name, ingredients) {
this.name = name;
this.ingredients = [];
}
var recipe1 = new Recipe('Granola Energy Bites', ['1 cup old-fashioned oats', '1/4 tsp salt', '1/4 tsp cinnamon']);
var recipe1Name = recipe1.name;
name1.innerHTML = recipe1Name;
var recipe1Ingredients = recipe1.ingredients[0];
ingredients1.innerHTML = recipe1Ingredients;
答案 0 :(得分:2)
在JavaScript的第3行中,您将成分定义为一个空数组。您可以通过编写
来解决此问题this.ingredients = ingredients
相反。如果愿意,您还可以使用一个称为解构的漂亮工具,并且可以将其写为
this.ingredients = [...ingredients]
答案 1 :(得分:0)
请先尝试学习调试。您的问题是您没有对Ingredients参数做任何事情。
您的功能应该是:
function Recipe(name, ingredients) {
this.name = name;
this.ingredients = ingredients;
}
底部的代码也不正确,应该是:
var recipe1 = new Recipe('Granola Energy Bites', ['1 cup old-fashioned oats', '1/4 tsp salt', '1/4 tsp cinnamon']);
var recipe1Name = recipe1.name;
document.getElemendById("name1").innerHTML = recipe1Name;
var recipe1Ingredients = recipe1.ingredients;
insertToIngredients = "";
for (var i = 0; i<recipe1Ingerdients.length; i++) {
insertToIngredients = insertToIngredients + "<br>"+ recipe1Ingredients[i];
}
document.getElementById("ingredients1").innerHTML = insertToIngredients;