以 Javascript 字符串显示 HTML 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11092182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:04:28  来源:igfitidea点击:

Display HTML code in Javascript string

javascripthtml

提问by tristanojbacon

I hope the title explains what I'd like to achieve. If not, please read on!

我希望标题解释了我想要实现的目标。如果没有,请继续阅读!

I am currently coding a Lorem Ipsum generator (as a learning experience, though I may have it on my site for S&G's)

我目前正在编写 Lorem Ipsum 生成器(作为学习经验,虽然我可能在我的网站上有它供 S&G 使用)

So far, I've managed to get the code to output a random sentence from a list, into the text box. I've also created a generator for creating Lorem Ipsum bullet lists. Whenever someone generates some text via the tool, I'd like to have one box with the formatted text (paragraphes, bulleted, etc) and then another box with the raw HTML code, so designers can just copy and paste the code straight into their coding program. So far, I've sorted out the formatted text box, but I'm having issues with the raw HTML.

到目前为止,我已经设法将代码从列表中随机输出一个句子到文本框中。我还创建了一个用于创建 Lorem Ipsum 项目符号列表的生成器。每当有人通过该工具生成一些文本时,我都希望有一个带有格式化文本(段落、项目符号等)的框,然后是另一个带有原始 HTML 代码的框,这样设计人员就可以将代码直接复制并粘贴到他们的编码程序。到目前为止,我已经整理了格式化的文本框,但是原始 HTML 有问题。

This is what I've got so far:

这是我到目前为止所得到的:

[Obviously there's a var listArray at the beginning, but I won't bother adding that.]

[很明显,开头有一个 var listArray,但我不会费心添加它。]

var randomList = listArray[(Math.floor(Math.random() *listArray.length))]

document.getElementById("textarea").innerHTML = "<li>" + (randomList) + "</li>" + "<li>" + (randomList) + "</li>" + "<li>" + (randomList) + "</li>";
document.getElementById("textarea-code").innerHTML = "<li>" + randomList + "</li>" + "<li>" + randomList + "</li>" + "<li>" + randomList + "</li>";}

The second innerHTML line is just a copy of the first, and is the line I want to work on.

第二行innerHTML 只是第一行的副本,也是我想要处理的行。

How do I get that second line to output:

如何让第二行输出:

<li> Line 1 </li>
<li>li Line 2 </li>

into the HTML text box, instead of putting the list items into a bulleted point?

放入 HTML 文本框中,而不是将列表项放入项目符号点?

采纳答案by tristanojbacon

I worked it out! :D

我解决了!:D

For those of you who are interested, I used ASCII codes for each of the characters required to make up the <, /, and >.

对于那些感兴趣的人,我对组成 <、/ 和 > 所需的每个字符都使用了 ASCII 代码。

For example: <li> is

例如: <li> 是

&#60;li&#62;

Hope that helps someone else!

希望能帮助别人!

回答by pete

For the second line, use innerTextnot innerHTML

对于第二行,使用innerTextnotinnerHTML

document.getElementById("textarea-code").innerText = 'your html code'