gpt4 book ai didi

javascript - inner.HTML 不在 if 函数内居中

转载 作者:行者123 更新时间:2023-11-28 18:19:16 26 4
gpt4 key购买 nike

代码示例:

var msg = document.getElementById("message");

//constructor
function person(name,birthMonth,profession){
//set default values to a person
this.name = name || "No Name";
this.birthMonth = birthMonth || "No Month";
this.profession = profession || "Nobody";

//construction of the display function
this.display=function (){
msg.innerHTML += "<center><p>" + this.name + " " + "was born on " + this.birthMonth + " and they are a " + this.profession + ". "

//Month comparisons
if (this.birthMonth=="April"){
msg.innerHTML += "They are meh because they were born in April.(eww)"
}
else if (this.birthMonth=="January"){
msg.innerHTML += "They are the best because they were born in the <strong>best month!</strong>"
}
else {
msg.innerHTML += "They are okay, at best."
}
//close paragraph tag
msg.innerHTML += "<hr></p></center>"
}

}

问题:为什么 if/else 语句中的 msg.innerHTML 不居中?中心标签不应该捕获它们吗?在 HTML 输出中,if/else 之前的第一个语句居中。另外, hr 打印正确,所以我相信它也能输出。

谢谢!

最佳答案

当第一个innerHTML被调用时,浏览器会自动关闭中心标签。

使用完整消息构建一个字符串变量,然后在末尾设置innerHTML - 当您关闭中心标记时,浏览器将不需要执行任何操作,您的文本将根据您的需要呈现。

this.display=function (){
var mess = '';
mess += "<center><p>" + this.name + " " + "was born on " + this.birthMonth + " and they are a " + this.profession + ". "

//Month comparisons
if (this.birthMonth=="April"){
mess += "They are meh because they were born in April.(eww)"
}
else if (this.birthMonth=="January"){
mess += "They are the best because they were born in the <strong>best month!</strong>"
}
else {
mess += "They are okay, at best."
}
//close paragraph tag
mess += "<hr></p></center>"
msg.innerHTML = mess;
}

关于javascript - inner.HTML 不在 if 函数内居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40221027/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com