是否可以通过javascript函数插入代码块?

时间:2020-08-20 22:25:28

标签: javascript html

例如给出这样的东西

const stuff = [{"a": "b"}]
const inhtml = document.querySelector(".exists")
const pre = document.createElement("pre")
pre.appendChild(document.createTextNode(stuff))
inhtml.appendChild(pre)

我希望它在代码块中动态输出数组[{“ a”:“ b”}]

除了只输出[Object object ...]

1 个答案:

答案 0 :(得分:0)

您可以使用JSON.stringify()来显示文本:

const stuff = [{"a": "b"}];
const inhtml = document.querySelector("div#main");
const pre = document.createElement("pre");
const code = document.createElement("code");

code.innerHTML = JSON.stringify(stuff, null, '\t');
code.style.backgroundColor = '#ebccca';

pre.appendChild(code);

inhtml.appendChild(pre);
<p>Code goes below here</p>

<div id="main"></div>