我目前正在尝试以html显示我的对象和方法。我的目标是在html中有2个按钮(info vacc1,info vacc2,用于打印对象的信息。我的目标是将其输出到按钮的正下方
这是我的js代码:
function myVaccines(companyName, vaccName, Type, numberOfShots, doesNotContain){
this.companyName = companyName;
this.vaccName = vaccName;
this.Type = Type;
this.numberOfShots = numberOfShots;
this.doesNotContain = doesNotContain;
}
var vacc1 = Vacc("Pfizer-BioNTech","BNT162b2","mRNA","2 shots, 21 days apart","Eggs, Preservatives, Latex");
var vacc2 = Vacc("Moderna","mRNA-1273","mRNA","2shots, 28 days apart","Eggs, Preservatives, Latex",)
这是我的html :(尚不知道在此放置什么)
<button onclick="myVaccines(vacc1)">
Information Vaccine 1
</button>
<p>Output1?</p>
<button onclick="myVaccines(vacc2)">
Information Vaccine 2
</button>
<p>Output2?</p>
在这里使用JavaScript类,就像我为这种情况所建议的那样。在其中定义了一个函数,该函数显示对象的属性,类似于toString()
Java中的方法。
display() {
return this.companyName + " " + this.vaccName + " " + this.Type + " " + this.numberOfShots + " " + this.doesNotContain;
}
提供您的按钮ID,并为每个按钮定义一个eventListener,以在单击时进行监听。
document.getElementById("first").addEventListener('click', function() {
onclick调用对象的display()函数并在输出段落中显示内容
class Vaccines {
constructor(companyName, vaccName, Type, numberOfShots, doesNotContain) {
this.companyName = companyName,
this.vaccName = vaccName,
this.Type = Type,
this.numberOfShots = numberOfShots,
this.doesNotContain = doesNotContain
}
display() {
return this.companyName + " " + this.vaccName + " " + this.Type + " " + this.numberOfShots + " " + this.doesNotContain;
}
}
var vacc1 = new Vaccines("Pfizer-BioNTech", "BNT162b2", "mRNA", "2 shots, 21 days apart", "Eggs, Preservatives, Latex");
var vacc2 = new Vaccines("Moderna", "mRNA-1273", "mRNA", "2shots, 28 days apart", "Eggs, Preservatives, Latex", )
document.getElementById("first").addEventListener('click', function() {
document.getElementById("out1").innerHTML = vacc1.display();
});
document.getElementById("second").addEventListener('click', function() {
document.getElementById("out2").innerHTML = vacc2.display();
});
<button id="first">
Information Vaccine 1
</button>
<p id="out1">Output1?</p>
<button id="second">
Information Vaccine 2
</button>
<p id="out2">Output2?</p>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句