making new line in JS

二次信任 提交于 2019-12-12 21:52:42

问题


Hi I have this JS code

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

why whan I put the br tag in its just writs the br tag on the screen and there is now break between the line? I alsow tried to put the "\n" and it doesnt work too. why?


回答1:


To make the <br/> tag become an element, you'd need to set the innerHTML instead of innerText.

The \n approach would have also worked. Only, whitespaces don't appear in the layout usually. If you set the CSS style of the #demo element to white-space:pre-wrap;, the linebreak will show up.




回答2:


You need to set innerHTML rather than innerText. However beware of different kinds of security attacks and sanitize the user-provided text (i.e. name).




回答3:


you are setting the innerText which will only set the Text of the Element. Try :

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


来源:https://stackoverflow.com/questions/12422201/making-new-line-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!