首页 > 解决方案 > 如何使用 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>

标签: javascripthtmljsonundefined

解决方案


推荐阅读