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

标签 javascript html

代码示例:

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/

相关文章:

javascript - 在MVC 4.0母版页中加载jquery

php - 需要用PHP保存数据的HTML表单

javascript - 窗口 keyup 事件 - 您可以在页面处于事件状态时随时监听 keyup 吗?

html - 为什么 google 字体在 safari 上的加载方式与 chrome 不同,我该如何解决?

HTML:无法让 DIV 紧紧包裹内部 div

html - 如何使用 CSS 创建可滚动的 HTML 表格列?

jquery - Bootstrap 导航问题

javascript - 检查单击的两个元素及其数量

javascript - 设置十进制数的格式

javascript - 如何在一页布局中设置固定位置图像