внутреннее.HTML не центрируется внутри функций if

#javascript #html

#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>"
    }

}
  

Вопрос: Почему msg.innerHTML не центрируется внутри операторов if / else? Разве теги center не должны их перехватывать? В выводе HTML первые операторы перед if / else центрируются. Кроме того, hr печатает правильно, поэтому я уверен, что он выводит и это.

Спасибо!

Комментарии:

1. Потому что <center> не работает. Проверьте text-align вместо этого.

2. Интересно, потому что первая строка центрирована. Я предпочитаю сам выравнивать текст, просто играл с innerHTML.

3. @MikeC то, что он устарел, не означает, что он не поддерживается; я все еще могу центрировать элементы в Chrome 53 с его помощью.

4. @Polyov Верно. Полагаю, мне следовало сказать, что вы должны рассматривать его как неподдерживаемый. ответ hairmots соответствует реальной проблеме.

5. Верно, но «устаревший» означает «может быть удален в любое время», поэтому использовать его опасно — лучше придерживаться поддерживаемых элементов API.

Ответ №1:

Браузер автоматически закрывает тег center при первом вызове innerHTML.

Создайте строковую переменную с полным сообщением, затем установите innerHTML в конце — когда вы закроете тег center, браузеру ничего не нужно будет делать, и ваш текст будет отображаться так, как вы требуете.

 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;
}
  

Ответ №2:

«Тег не поддерживается в HTML5. Вместо этого используйте CSS. » Используйте text-align: center; вместо этого.

Комментарии:

1. Но проблема не в этом. Несмотря на <center> снижение стоимости, он по-прежнему поддерживается в современных браузерах.

Ответ №3:

Использование фрагментов документа и CSS обеспечивает более быстрые ответы

 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() {
    var frag = document.createDocumentFragment();
    var para = frag.appendChild(document.createElement("p"));
        para.className = "message";
        para.appendChild(document.createTextNode(this.name   " "   "was born on "   this.birthMonth   " and they are a "   this.profession   ". "));

    //Month comparisons
    if (this.birthMonth == "April") {
        para.appendChild(document.createTextNode("They are meh because they were born in April. (eww)"));
    } else if (this.birthMonth == "January") {
        para.appendChild(document.createTextNode("They are the best because they were born in the best month! "));
        var strong = para.appendChild(document.createElement("strong"));
            strong.textContent = "best month!";
    } else {
        para.appendChild(document.createTextNode("They are okay, at best."));
    }

    msg.appendChild(frag);
    };

}

var test1 = new person("Bob", "April", "Developer");
    test1.display();
var test2 = new person("Bobby", "January", "Developer");
    test2.display();
var test3 = new person("Rob", "else", "Developer");
    test3.display();  
 .message {
  text-align: center;
}  
 <div id="message"></div>