html 在html文件中循环遍历数组并展示(1)

用html文件实现一个简单的遍历数组并输出到页面上面

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>html.forEach</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      html {
        width: 100%;
      }

      .item-title {
        font-size: 26px;
        font-weight: bold;
      }

      .item-question {
        margin-top: 20px;
        font-weight: bold;
        font-size: 20px;
      }

      .item-answer {
        margin-top: 10px;
        font-size: 18px;
        margin-left: 10px;
        line-height: 28px;
      }

      li {
        list-style: none;
      }
    </style>
  </head>

  <body>

    <div class="recommend-list">
      <ul>
        <li>
          <div>
            <p class="item-title"></p>
            <p class="item-question"></p>
            <p class="item-answer"></p>
          </div>
        </li>
      </ul>
    </div>
  </body>
  <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
  <script>
    var mainStr = ''
    //自定义数组
    var mainArr = [
      {
        title: '这是第一级',
        children: [
          {
            question: '这是第一级1-1',
            answer: '这是第一级1-1描述',
          },
          {
            question: '这是第一级1-2',
            answer: '这是第一级1-2描述',
          },
        ],
      },
      {
        title: '这是第二级',
        children: [
          {
            question: '这是第二级2-1',
            answer: '这是第二级2-1描述',
          },
          {
            question: '这是第二级2-2',
            children: ['这是第二级2-2-1', '这是第二级2-2-2'],
          },
        ],
      },
      {
        title: '这是第三级',
        children: [
          {
            question: '这是第三级3-1',
            answer: '这是第三级3-1描述',
          },
        ],
      },
    ]
    /*
     *.join('')的作用是去掉map循环后返回多余的逗号
     */
    mainArr.forEach((e) => {  // forEach遍历大数组
      mainStr += `
                  <li>
                    <div>
                      <p class="item-title">${e.title}</p>
                      ${e.children.map((element, index) => {  // 用来遍历每一项中的子列表
                        let ele = `
                          <p class="item-question">${index + 1}.${element.question}</p>`
                          if(element.children != undefined){element.children.forEach((item) => { // 遍历子列表中的子列表
                            ele += `<p class="item-answer">${item}</p>`
                          })} else {
                            ele += `<p class="item-answer">${element.answer}</p>`
                          }

                        return ele
                      }).join('')}
                    </div>
                  </li>`
    })
    //拼接完字符串数组后用innerHTML把它渲染到父元素中
    document.querySelector('ul').innerHTML = mainStr


  </script>
</html>

展示效果:

 参考:https://blog.csdn.net/hh18700418030/article/details/106722474

posted @ 2020-12-10 11:04  小生不才。  阅读(6520)  评论(0编辑  收藏  举报