首页 > 解决方案 > 是否可以从 javascript 函数中插入代码块?

问题描述

例如给出这样的东西

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 ...]

标签: javascripthtml

解决方案


您可以使用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>


推荐阅读