我是靠谱客的博主 玩命大雁,这篇文章主要介绍将给定的数据动态加入到创建的表格中(源代码),现在分享给大家,希望可以做个参考。

本篇文章给大家带来的内容是关于将给定的数据动态加入到创建的表格中(源代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

思路:

  1. 创建 table + thead + tbody

  2. 创建 tr + th

  3. 创建每一行的 tr + td

  4. 加到页面中

注:最后再加到页面中的原因是每将一个元素加到页面一次,页面便会刷新一次,因此先在内存中创建好表格再一次性的加到页面中,页面只需刷新一次,减少性能的损失。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body></body><script> var data = [ { name : "jim1", age : 18, gender : "male"}, { name : "jim2", age : 19, gender : "female"}, { name : "jim3", age : 20, gender : "female"}, { name : "jim4", age : 21, gender : "male"} ]; function createElement( tag ) { return document.createElement( tag ); } var table = createElement( "table" ); var thead = createElement( "thead" ); var tbody = createElement( "tbody" ); table.appendChild( thead ); table.appendChild( tbody ); var trhead = createElement( "tr" ); thead.appendChild( trhead ); for ( var k in data[ 0 ] ){ th = createElement( "th" ); th.appendChild( document.createTextNode( k ) ); trhead.appendChild( th ); } for ( var i = 0; i < data.length; i++){ var tr = createElement( "tr" ); for ( var j in data[ i ]){ td = createElement( "td" ); td.appendChild( document.createTextNode( data[i][j] )); tr.appendChild( td ); } tbody.appendChild( tr ); } //table.setAttribute("border","1px"); //或直接设置table.border = "1px";两者等价。 table.border = "1px"; table.cellspadding = 0; table.setAttribute("align","center"); table.style.textAlign = "center"; table.setAttribute("borderColor","skyBlue"); table.setAttribute("cellspacing",0); document.body.appendChild( table );</script></html>
登录后复制

以上就是对将给定的数据动态加入到创建的表格中(源代码)的全部介绍,本文内容紧凑,希望大家可以有所收获,更多请关注靠谱客。

以上就是将给定的数据动态加入到创建的表格中(源代码)的详细内容,更多请关注靠谱客其它相关文章!

最后

以上就是玩命大雁最近收集整理的关于将给定的数据动态加入到创建的表格中(源代码)的全部内容,更多相关将给定内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(111)

评论列表共有 0 条评论

立即
投稿
返回
顶部