如何使用javascript从json返回html?

omtl5h9j  于 2021-09-23  发布在  Java
关注(0)|答案(0)|浏览(193)

我在index.html和javascript中有一些json,它们最终将遍历json并根据其“\u类型”将其拆分。理想情况下,它会看到一个“bodytext”,并将该对象放在自己的div中,并具有特定的样式。
我可以在登录时在控制台中显示内容,但当我尝试返回它时,它以未定义的形式出现。我做错了什么?
my 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>

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题