我有一个小程序,你有一份冰淇淋口味清单,电脑使用“console.log();”打印句子和味道。我已经开始了这个项目,它看起来像这样:
var randomFlavour = Math.random() * 10;
if (randomFlavour < 1) {
var randomFlavour = "chocolate";
} else if (randomFlavour < 2) {
var randomFlavour = "vanilla";
} else if (randomFlavour < 3) {
var randomFlavour = "pistachio";
} else if (randomFlavour < 4) {
var randomFlavour = "strawberry";
} else if (randomFlavour < 5) {
var randomFlavour = "cotton candy";
} else if (randomFlavour < 6) {
var randomFlavour = "cookie dough";
} else if (randomFlavour < 7) {
var randomFlavour = "bubblegum";
} else if (randomFlavour < 8) {
var randomFlavour = "peanut butter";
} else if (randomFlavour < 9) {
var randomFlavour = "mint";
} else {
var randomFlavour = "gingerbread man";
}
console.log("Hello. I would like to have" + " " + randomFlavour + " " + "ice cream please.");
问题是;这只会在控制台中打印,我希望打印的文本在<p>
段落中转换,是否可能?
答案 0 :(得分:1)
创建<p></p>
元素,编辑innerHTML
,添加到DOM
:
var par = document.createElement('p')
par.innerHTML = "Hello. I would like to have " + randomFlavour + " ice cream please."
document.body.appendChild(par)
答案 1 :(得分:1)
而不是console.log();
你可以使用,
document.getElementById("idhere").innerHTML = "your string here";
for&#34; idhere&#34;把你要改变的段落的id。
答案 2 :(得分:1)
首先,您需要访问<p>
元素。
您需要为您的元素分配一个ID:
<p id="myPar">
</p>
然后你可以像这样进入js:
var par = document.getElementById('myPar');
然后要设置其文字,您可以使用innerHTML
par.innerHTML = randomFlavour;
答案 3 :(得分:-1)
在同一级别上你写了console.log()做一个document.write();与输出。 console.log只输出到控制台,而document.write写入你的html页面。