javascript - 是否可以从 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 ...]
解决方案
您可以使用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>
推荐阅读
- object - 嵌套可分配组件
- c++ - VSCode:对“特定类”的未定义引用
- gitlab - Gitlab CI/CD 如何
- python - SetUp 在 odoo 单元测试中做了什么?
- r - is.data.frame(data) 中的错误:找不到对象“test_data”
- scala - SCALA:带条件的折叠方法
- python - PyCharm 未正确从导入中提取文档字符串
- python - 如何防止用户在频道中发送多条消息?
- python - ValueError:检查目标时出错:预期 time_distributed_1 具有 3 个维度,但得到的数组具有形状 (18912, 35)
- c# - 可以依赖自动属性支持字段名称吗?