用js来写html的一个小小随机生成成绩表 发表于 2017-04-27 | 分类于 demo | 运行效果这是学习js代码调试时写的,代码本身很简单,主要为了调试js,html代码123456789101112<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>学生成绩表</title> <link rel="stylesheet" href = "css/index.css" ></head><body> <div id = "scoreTable"></div> <script src = "js/index.js"></script></body></html> css代码12345678910111213141516171819202122232425262728293031.header { width: 810px; margin: 0 auto; position: relative;}.title { text-align: center; font-size: 2em;}#refresh { position: absolute; right: 0; top: 8px;}table { margin: 0 auto; border: 1px solid #000; border-collapse: collapse;}table th { border: 1px solid #000; background-color: #00ffef;}table td { width: 200px; border: 1px solid #000; text-align: center;}.changeColor { background-color: #eceee3;} js代码1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465var students = [];var lastName = ["赵","钱","孙","李","周","吴","王","许","文","刘","马","范","欧阳","翁","陈"];var firstName = ["伸义","志泽","梦洁","皓轩","博文","懿轩","煜城","诗茵","子轩","梦璐","凌菲","天磊"];//学生的函数构造器function Student(id,lastName,firstName,age,score) { this.id = id; this.lastName = lastName; this.firstNmae = firstName; this.age = age; this.score = score;}//生成num个学生var produceStudent = function(num) { console.log("开始生成学生"); for(var i=0;i<num;i++) { var lastNameIndex = Math.floor(Math.random()*lastName.length); var firstNameIndex = Math.floor(Math.random()*firstName.length); var randomAge = Math.floor(Math.random()*3) + 15; var randomScore = Math.floor(Math.random()*(100+1)); var student = new Student(i+1,lastName[lastNameIndex],firstName[firstNameIndex],randomAge,randomScore); students.push(student); } console.log("所有学生生成成功"); return students;};//渲染学生数据var renderStudent = function(array) { var html = []; html.push("<div class = 'header'>"); html.push("<h3 class = 'title'>5班成绩统计</h3>"); html.push("<button id = 'refresh'>刷新</button>") html.push("</div>"); html.push("<table>"); html.push("<tr>"); html.push("<th>序号</th>"); html.push("<th>姓名</th>"); html.push("<th>年龄</th>"); html.push("<th>成绩</th>"); html.push("</tr>"); for(var j=0;j<array.length;j++) { if(j%2 == 1) { html.push("<tr class = 'changeColor'>"); } else { html.push("<tr>"); } //给每位学生填入数据 html.push("<td>" + array[j].id + "</td>"); html.push("<td>" + array[j].lastName + array[j].firstNmae +"</td>"); html.push("<td>" + array[j].age + "</td>"); html.push("<td>" + array[j].score + "</td>"); html.push("</tr>"); } html.push("</table>") return html;}var allStudent = produceStudent(50); //生成学生var allHtml = renderStudent(allStudent); //渲染学生数据document.getElementById("scoreTable").innerHTML = allHtml.join(""); //所有html加入文档document.getElementById("refresh").onclick = function() { window.location.reload();}; 运行链接: http://codepen.io/wzc/full/qrmoNj/(可能点重新生成按钮失效,直接刷新页面就可以重新生成了)