javascript - 如何使用 Javascript 从 json 返回 HTML?
问题描述
我的 index.html 和 javascript 中有一些 json,它们最终会通过 json 并根据其“_type”将其拆分。理想情况下,它会看到一个“bodyText”并将该对象放在它自己的具有特定样式的 div 中。
当我记录它时,我可以让内容显示在控制台中,但是当我尝试返回它时,它以未定义的形式出现。我究竟做错了什么?
我的 index.html 的一部分:
.
.
.
<div id="body"></div>
.
.
.
<script>
const bodyGrid = [
{
_type: "bodyText",
richText: `<div>
<h3>Body Text Element</h3>
<p>This could hold <strong>any</strong> html element</p>
<ul>
<li>item 1</li>
<li><a href="#"item 2</a></li>
</ul>
<p>Grid layout should be based on a limited number of columns (12 for content layout + 2 side columns (1fr each) to pad/center content = 14 total columns),
and an infinite number of rows.
</p>
<p>possibly column template should be something like <em>grid-template-columns: 1fr repeat(12, 75px) 1fr</em> that gives 900px grid in the middle.</p>
<p>Each element should place itself into the grid. Possibly by specifying a starting column and ending column.
Or a span of columns. AND maybe a span of rows.
</p>
</div>`,
rows: 1,
columns: 8,
startColumn: 2,
verticalAlign: "start",
horizontalAlign: "start",
}
];
</script>
<script type="module">
import BodyGrid from "/browser/BodyGrid.js";
document.getElementById("body").innerHTML = BodyGrid(bodyGrid);
</script>
然后是 BodyGrid.js:
import BodyText from "../bodytext/BodyText";
const BodyGrid = (bodyGrid) => {
bodyGrid.map((moduleObj) => {
const { _type } = moduleObj;
if (_type == "bodyText") {
return BodyText(moduleObj);
}
else {
return `Hey gurl hey`
}
});
};
export default BodyGrid;
BodyText.js:
const BodyText = ({ richText } = {}) => {
console.log(richText)
return richText;
};
export default BodyText;
显示的console.log(richText)
正是我想要的。
<div>
<h3>Body Text Element</h3>
<p>This could hold <strong>any</strong> html element</p>
<ul>
<li>item 1</li>
<li><a href="#"item 2</a></li>
</ul>
<p>Grid layout should be based on a limited number of columns (12 for content layout + 2 side columns (1fr each) to pad/center content = 14 total columns),
and an infinite number of rows.
</p>
<p>possibly column template should be something like <em>grid-template-columns: 1fr repeat(12, 75px) 1fr</em> that gives 900px grid in the middle.</p>
<p>Each element should place itself into the grid. Possibly by specifying a starting column and ending column.
Or a span of columns. AND maybe a span of rows.
</p>
</div>
但是,在浏览器中,它显示未定义。
<div id="body">undefined</div>
解决方案
推荐阅读
- storage - IBM Watson 知识:为什么存储不会减少
- python - 在 Visual Studio Code 中使用 python 时无法使用 input() - Input() 无法再次获取任何行
- java - 如何在jsp的查询中使用字符串变量
- ios - 使用 Swift 将录音上传到 Firebase
- php - $_SESSION 变量在我将其设置为 null 之前为 null
- performance - LUA 表选择的性能明智
- apache-spark - 如何将一个RDD拆分成多个RDD并相互比较
- php - UnexpectedValueException laravel:协议错误
- rabbitmq - Spring Initializer - 缺少 Zipkin 依赖项?
- javascript - Gatsby JS - 多个页面拉入具有不同类别的降价文件