在JS中创建新行

时间:2012-09-14 09:57:11

标签: javascript newline

嗨,我有这个JS代码

  function myFunction() {
  var g; 
var d = new Date().getDay();
switch (d) {
    case 0:
        g = "Today it's Sunday";
        break;
    case 1:
        g = "Today it's Monday";
        break;
    case 2:
        g = "Today it's Tuesday";
        break;
    case 3:
        g = "Today it's Wednesday";
        break;
    case 4:
        g = "Today it's Thursday";
        break;
    case 5:
        g = "Today it's Friday";
        break;
    case 6:
        g = "Today it's Saturday";
        break;
    default:
        x = "Looking forward to the Weekend";
}


var y; //popup

var name = prompt("Please enter your name", " (your name is here)");

if (name != null) {
    y = 'How are you today?';
    document.getElementById("popup").innerHTML = y; //
}
var x = ""; //שעה
var time = new Date().getHours();
if (time < 12)  //תנאי
{
    x = "Have a beautiful morning " + name + '! ';
}
else if (time < 16) {
    x = "Great noon! Enjoy this day " + name + '!';
}
else if (time < 19) {
    x = "Great afternoon! Enjoy them " + name + '!';
}
else if (time < 23) {
    x = "Good evening! have some fun and take some rest befor the day over" + name + '!';
}

document.getElementById("demo").innerText = x + "<br/>" + g; 
}

为什么我把br标签放在屏幕上的br标签上,现在它之间有断线? 我也试图把“\ n”放在一起,它也不起作用。为什么呢?

3 个答案:

答案 0 :(得分:3)

您需要设置innerHTML而不是innerText。但请注意不同类型的安全攻击和sanitize用户提供的文本(即name)。

答案 1 :(得分:1)

您正在设置innerText,它只会设置元素的文本。 试试:

document.getElementById("demo").innerHTML = x + "<br/>" + g;  

答案 2 :(得分:1)

要使<br/>标记成为元素,您需要设置innerHTML而不是innerText

\n方法也会起作用。只是,空格通常不会出现在布局中。如果您将#demo元素的CSS样式设置为white-space:pre-wrap;,则会显示换行符。