<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ys-js</title> </head> <body> <h1>原生JS</h1> <input type="button" value="拼接" onclick="clickMe()"> <div id="text" style="background-color: rgb(135, 206, 53);"></div> <script> function clickMe(){ var isHtml = ""; //数组 var arr = [ {"name":"xiao ming","id":1,"info":"及格"}, {"name":"xiao hong","id":2,"info":"及格"}, {"name":"xiao fei","id":3,"info":"不及格"}, ]; for(var i = 0; i < arr.length; i++){ console.log(arr[i]) // isHtml += '<div id="text" style="background-color: #eee;">'; isHtml += '<p>'+arr[i].name+'>>>'+arr[i].info+'</p>'; // isHtml += '<p>'+arr[i].info+'</p>'; // isHtml += '</div>'; }; console.log(isHtml) document.getElementById("text").innerHTML=isHtml; //把内容拼接到id为text的容器中 //alert(arr.length) } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body lang="en"> <div id="list"></div> <script type="text/javascript"> //假的数据源 let datas = [ { "id": 1, "name": "tom", "age": 19 }, { "id": 2, "name": "alis", "age": 23 } ] //空变量 let htmlData = "" //循环数据源得到数据拼接 datas.forEach(p => { htmlData += `<li>${p.id} --- ${p.name} --- ${p.age}</li>` }); //获取div标签的id值 let list = document.getElementById('list') // alert(htmlData) //把数据插入div容器中 list.innerHTML = htmlData; </script> </body> </html>