我目前正在使用OOP来显示烹饪食谱。 一切都很好,除了我使用document.write
方法时。 在显示价格
时,文本显示为“$2.00未定义”和“$6.00未定义”。 下面是我的代码:
<html>
<body>
<p id = "p"></p>
<script>
function Recipe(name, ingredients, price) {
this.name = name;
this.ingredients = ingredients;
this.price = price;
}
function describe(name, ingredients, price) {
document.write("<h2> Recipe name: " + name + "</h2> Ingredients: " + ingredients + "<br />Price: " + price);
}
var instantRamen = new Recipe("Ramen", "Ramen noodles, hot water, salt, (optional) green pepper", "$2.00");
var Bagel = new Recipe("Ham and cheese bagel", "Bagel (preferably an everything bagel), ham, cheese (of any type), pepper (just a little)", "$6.00");
document.write(describe(instantRamen.name, instantRamen.ingredients, instantRamen.price));
document.write(describe(Bagel.name, Bagel.ingredients, Bagel.price));
</script>
</body>
</html>
预期的结果是类似“食谱名称:拉面(linebreak)配料:拉面,热水,盐,(可选)青椒(linebreak)价格:$2.00”,但价格变成了“$2.00未定义”。 其他都管用。
我最初认为在创建InstantRamen
和Bagel
实例时有问题,因此尝试更改一些语法,但没有效果。
问题是您正在调用document.write
函数中的descripe
函数。 它写的是未定义的,因为describe不返回任何
正在发生的事情是:首先,descripe
函数在文档中写入html文本。 然后,您尝试在文档中写入descripe
函数的返回。
您不需要将describe
函数放在document.write
中。只需使用所需的参数调用它。
您可以像这样返回
您的函数。
因为您没有返回任何值。 Thatsy未定义
null
function Recipe(name, ingredients, price) {
this.name = name;
this.ingredients = ingredients;
this.price = price;
}
function describe(name, ingredients, price) {
return "<h2> Recipe name: " + name + "</h2> Ingredients: " + ingredients + "<br />Price: " + price;
}
var instantRamen = new Recipe("Ramen", "Ramen noodles, hot water, salt, (optional) green pepper", "$2.00");
var Bagel = new Recipe("Ham and cheese bagel", "Bagel (preferably an everything bagel), ham, cheese (of any type), pepper (just a little)", "$6.00");
document.write(describe(instantRamen.name, instantRamen.ingredients, instantRamen.price));
document.write(describe(Bagel.name, Bagel.ingredients, Bagel.price));
<html>
<body>
<p id = "p"></p>
</body>
</html>
现在它起作用了
null
<html>
<body>
<p id = "p"></p>
<script>
function Recipe(name, ingredients, price) {
this.name = name;
this.ingredients = ingredients;
this.price = price;
}
function describe(name, ingredients, price) {
document.write("<h2> Recipe name: " + name + "</h2> Ingredients: " + ingredients + "<br />Price: " + price );
}
var instantRamen = new Recipe("Ramen", "Ramen noodles, hot water, salt, (optional) green pepper", "$2.00");
var Bagel = new Recipe("Ham and cheese bagel", "Bagel (preferably an everything bagel), ham, cheese (of any type), pepper (just a little)", "$6.00");
//edited
describe(instantRamen.name, instantRamen.ingredients, instantRamen.price);
describe(Bagel.name, Bagel.ingredients, Bagel.price);
document.getElementById("p").innerHTML = "Your browser version is " + navigator.appVersion;
</script>
</body>
</html>