用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, .item-bg { width: 150px; height: 200px; margin-top: 10px; font-size: 18px; margin-left: 10px; line-height: 28px; background-position: center; background-size: cover; background-repeat: no-repeat; } li { list-style: none; } </style> </head> <body> <div class="recommend-list"> <ul> <!-- <li> <div> <p class="item-title"></p> <p class="item-question"></p> <img class="item-answer" src="" alt=""> <div class="item-bg" style="background-image: url('');"></div> </div> </li> --> </ul> </div> </body> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script> <script> var mainStr = '' var baseUrl = 'http://81.70.146.54:2222/' // 此地址为真是地址 getPageTotalAndDataTotal() function getPageTotalAndDataTotal(page) { // 获取页数与数据总数 $.ajax({ url: baseUrl + 'news/findStatus', type: 'post', dataType: 'json', // 数据使用JSON格式进行传输 success: function (data) { // 成功回调,返回的数据根据结果进行相应的会处理 // console.log(data) console.log(data.data) var status = data.data; if (data.code == '1') { // 成功获取到数据拎出去单写 init(status) } }, }) } /* *.join('')的作用是去掉map循环后返回多余的逗号 */ function init(status){ status.forEach((e) => { // forEach遍历大数组 并且内容赋值 mainStr += ` <li> <div> <p class="item-title">${e.title}</p> <p class="item-question">${e.content}</p> <img class="item-answer" src="${e.imageUrl}" alt=""> <div class="item-bg" style="background-image: url('${e.imageUrl}');"></div> </div> </li>` }) //拼接完字符串数组后用innerHTML把它渲染到父元素中 document.querySelector('ul').innerHTML = mainStr } </script> </html>
效果展示: