近来的项目须要模仿一个json花样的数据,
花样以下
{
"studentA": [
{
"grade": "A",
"class": "B",
"course": {
"a": "0-100",
" b ": "0-100"
}
}
],
"studentB": [
{
"grade": "A",
"class": "B",
"course": {
"a": "0-100",
" b ": "0-100"
}
}
]
}
我们要完成这个功用,
1、变量和数组声明
var score= new Array();
var num1=d3.range(6).map(d3.random.normal(0.8,0.1));
// 随机天生年级
var grades=[1,2,3,4];
// 随机天生班级
var classes=[1,2];
//随机天生姓
var lastnames=["赵","钱","孙","李","周","吴","郑","王","冯","陈","卫","蒋","沈","韩","杨","朱","秦","许","何","吕","施","张"];
//随机天生名
var firstnames=["伟","芳","娜","丽","强","静","敏","磊","军","涛","明","刚","洁","斓","文","华","金","斌","波","辉","亮","超"];
2、组织函数
function getStu(){
var stu = {
"name":"",
"detail":{}
};
var lastname=lastnames[Math.floor(Math.random()*lastnames.length+1)-1];
var firstname=firstnames[Math.floor(Math.random()*firstnames.length+1)-1];
var grade=Math.floor(Math.random()*4+1);
var classe=Math.floor(Math.random()*2+1);
stu.name = lastname+firstname;
stu.detail.grade = grade;
stu.detail.class = classe;
stu.detail.score = num1.map(function(d){
return d*100>100?100:Math.round(d*100);
});
return stu;
}
下面我们用innerHTML给页面中写入内容:
temp.innerHTML='
<div id="copy">
{<br>
<span>
"<label></label>":[
<br> {
<br>
"grade":"<label></label>",<br>
"class":"<label></label>",<br>
"course":{<br>
"计算机网络":"<label></label>",<br>
"大学英语":"<label></label>",<br>
"Web前端开辟":"<label></label>",<br>
"C言语程序设计":"<label></label>",<br>
"数据结构":"<label></label>",<br>
"大学物理":"<label></label>",<br>
}
<br>
}<br>
],<br>
</span>}
</div>';
temp.getElementsByTagName("label")[0].innerHTML=stu.name;
temp.getElementsByTagName("label")[1].innerHTML=stu.detail.grade;
temp.getElementsByTagName("label")[2].innerHTML=stu.detail.class;
temp.getElementsByTagName("label")[3].innerHTML=stu.detail.score[0];
temp.getElementsByTagName("label")[4].innerHTML=stu.detail.score[1];
temp.getElementsByTagName("label")[5].innerHTML=stu.detail.score[2];
temp.getElementsByTagName("label")[6].innerHTML=stu.detail.score[3];
temp.getElementsByTagName("label")[7].innerHTML=stu.detail.score[4];
temp.getElementsByTagName("label")[8].innerHTML=stu.detail.score[5];
document.getElementById("main").appendChild(temp);
}