如何从脚本创建的文本换行

时间:2019-07-02 16:14:37

标签: javascript html

I'm trying to make a part of my website where you click on a title and then the description pops up and it works but I don't know how to add a new line/bullet points for it 

I've tried \n and that didn't work.

<body>

<button class = "text_buttons" type = "button" id = "Toast" onclick="myFunction()">Purpose▼</button>
<p id="cheese"></p>

<script>
function myFunction()
{
    if (document.getElementById("Toast").innerHTML =="Purpose▼") document.getElementById("Toast").innerHTML = "Purpose▲";
    else document.getElementById("Toast").innerHTML ="Purpose▼";

    if (document.getElementById("cheese").innerHTML == "") document.getElementById("cheese").innerHTML = "This is not what is actually displayed but it's jsut filler text that hopefully i can figure out to space correctly";
    else document.getElementById("cheese").innerHTML = "";
}
</script>
</body>

没有错误发生,我似乎无法理解。我尝试过在线查看一些东西,但是我发现的唯一东西是建议\ n的东西,但在这种情况下不起作用。

1 个答案:

答案 0 :(得分:0)

对于换行问题,在HTML中,<br>标签用作换行符。 \n用在脚本中,但在这里不起作用。如果您尝试使用要点,则<ul><li>标签用于无序列表将帮助您实现这一点。

<body>

<button class = "text_buttons" type = "button" id = "Toast" onclick="myFunction()">Purpose▼</button>
<p id="cheese"></p>

<script>
function myFunction()
{
    if (document.getElementById("Toast").innerHTML =="Purpose▼") document.getElementById("Toast").innerHTML = "Purpose▲";
    else document.getElementById("Toast").innerHTML ="Purpose▼";

    if (document.getElementById("cheese").innerHTML == "") document.getElementById("cheese").innerHTML = "This is a line<br>and another line<br>oh more lines<ul><li>And this is a bullet point<ul><li>And a nested bullet point</li></ul></li></ul>";
    else document.getElementById("cheese").innerHTML = "";
}
</script>
</body>

这可能会导致一些非常凌乱的代码。重复插入HTML片段时,模板引擎可以为您提供帮助。