如何在HTML文件中使用JavaScript变量?
我想打印变量数量在HTML中保存的值 这是我的JavaScript代码如何在HTML文件中使用JavaScript变量?,javascript,html,Javascript,Html,我想打印变量数量在HTML中保存的值 这是我的JavaScript代码 class Ingredient { constructor (name, dateBought, expiryDate, quantity, expired){ this.name = name; this.dateBought = dateBought; this.expiryDate = expiryDate; this.quantity = quantity; this.e
class Ingredient {
constructor (name, dateBought, expiryDate, quantity, expired){
this.name = name;
this.dateBought = dateBought;
this.expiryDate = expiryDate;
this.quantity = quantity;
this.expired = false;
}
isExpired(){
this.expired = true;
}
needReorder(){
console.log(this. name + "need to be reordered")
}
}
let cabbage = ("cabbage", new Date(2003,3,2), 23)
我试图在这样的HTML文件中显示数量,到目前为止没有打印任何内容
<script src="inventory.js">
var quantity = cabbage.quantity
</script>
<script>
document.write(quantity)
</script>
变量数量=卷心菜数量
文件写入(数量)
我知道我的HTML没有任何问题,因为这段代码工作得非常好
<script>
document.write("write something")
</script>
记录。写(“写东西”)
提前感谢:)
colla.quantity
,而不是在导入脚本中colla.quantity
,而不是在导入脚本中您需要正确访问
配料
类。在类声明中,quantity
应为第四个参数,因此应按如下方式传递该参数:
new Ingredient("cabbage", new Date(2003,3,2), 23, 10)
完整代码:
类成分{
构造函数(名称、购买日期、过期日期、数量、过期){
this.name=名称;
this.datebunded=datebunded;
this.expiryDate=expiryDate;
这个。数量=数量;
this.expired=false;
}
isExpired(){
this.expired=true;
}
需要重新排序(){
console.log(此.name+“需要重新排序”)
}
}
让卷心菜=新配料(“卷心菜”,新日期(2003,3,2),23,10)
document.write(colla.quantity)
您需要正确访问配料
类。在类声明中,quantity
应为第四个参数,因此应按如下方式传递该参数:
new Ingredient("cabbage", new Date(2003,3,2), 23, 10)
完整代码:
类成分{
构造函数(名称、购买日期、过期日期、数量、过期){
this.name=名称;
this.datebunded=datebunded;
this.expiryDate=expiryDate;
这个。数量=数量;
this.expired=false;
}
isExpired(){
this.expired=true;
}
需要重新排序(){
console.log(此.name+“需要重新排序”)
}
}
让卷心菜=新配料(“卷心菜”,新日期(2003,3,2),23,10)
document.write(colla.quantity)
我看不到difference@RuijieLu如果您仔细注意,这里有差异,它通过传递数量作为第四个参数来访问类。我看不到difference@RuijieLu如果你仔细注意的话,这里有不同之处,它通过传递数量作为第四个参数来访问类。我更新了答案,请检查@Ruijielu请不要使用文档。写入…您不能将外部源代码和内联脚本放在同一个标记中。我更新了答案,请检查@ruijielu请不要使用document.write…您不能将外部源代码和内联脚本放在同一个标记中。您能解释一下吗?我尝试了document.getElementById(“demo”).innerHTML=quantity;这对吗?对。由于脚本已经在html文件中导入,您可以像那样使用变量。重要的是,变量不应在第一个脚本(导入脚本)中使用,而应在另一个脚本中使用。谢谢您,它起到了作用。为什么需要第四个论点?我想让expired默认为false,真的很困惑如果你不定义第四个参数,它将是未定义的。你能解释一下吗?我尝试了document.getElementById(“demo”).innerHTML=quantity;这对吗?对。由于脚本已经在html文件中导入,您可以像那样使用变量。重要的是,变量不应在第一个脚本(导入脚本)中使用,而应在另一个脚本中使用。谢谢您,它起到了作用。为什么需要第四个论点?我想让expired默认为false,如果不定义第4个参数,它将是未定义的。
new Ingredient("cabbage", new Date(2003,3,2), 23, 10)