2

嗨,我有这个 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”,但它也不起作用。为什么?

4

3 回答 3

3

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

于 2012-09-14T09:58:00.507 回答
1

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

document.getElementById("demo").innerHTML = x + "<br/>" + g;  
于 2012-09-14T10:00:33.270 回答
1

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

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

于 2012-09-14T10:01:35.697 回答