javascript做表

In this article I will demonstrate three ways of creating and populating an HTML table with JavaScript, examining the advantages and disadvantages of each.

在本文中,我将演示使用JavaScript创建和填充HTML表的三种方法,并探讨每种方法的优缺点。

The table in the screenshot below lists all 118 elements (types of atom) including their names, atomic numbers (the number of protons in their nucleii) and their chemical symbols (the abbreviations used in chemical formulae such as H2O or NaCl).

下方屏幕快照中的表格列出了所有118种元素(原子类型),包括它们的名称,原子序数(其原子核中的质子数)及其化学符号(在化学式中使用的缩写,例如H2O或NaCl)。

The table itself as well as its caption, column headings and rows are created dynamically from a data structure, in this case an array of objects, using JavaScript.

该表本身及其标题,列标题和行是使用JavaScript从数据结构(在本例中为对象数组)动态创建的。

Compared to other HTML elements tables are relatively complex and can be fiddly to create so it is worth spending some effort doing so in a way which is both efficient to run and easy to code.

与其他HTML元素相比,表相对复杂并且可以轻松地创建,因此值得花一些精力来以高效运行和易于编码的方式进行操作。

As I mentioned above I am using three different methods to create a table. These are:

正如我上面提到的,我正在使用三种不同的方法来创建表。 这些是:

  • Building the table as a single string of HTML which is then added to the document as a single operation将表构建为单个HTML字符串,然后将其作为单个操作添加到文档中
  • Using standard DOM manipulation methods, namely createElement, createTextNode and appendChild使用标准的DOM操作方法,即createElement,createTextNode和appendChild
  • Using table-specific methods, namely createCaption, insertRow and insertCell使用表特定的方法,即createCaption,insertRow和insertCell

I will discuss each in detail in the code descriptions below.

我将在下面的代码描述中详细讨论每个对象。

该项目 (The Project)

The project consists of the following files plus a CSS file and a graphic. Together they form a complete web app which you can clone or download from the Github repository to run in your browser,

该项目由以下文件以及CSS文件和图形组成。 它们共同构成了一个完整的网络应用,您可以从Github存储库中克隆或下载该应用,以在浏览器中运行该应用,

  • creatingtables.htmcreationtables.htm
  • creatingtables.jscreationtables.js
  • elements.jselements.js

资料来源 (The Data Source)

Before getting stuck into creating tables I need to briefly describe the data source. In the real world you would probably be populating a table from, for example, a data structure parsed from JSON obtained from a REST API. For this demo I have hard-coded the data into a static method of a class in elements.js which is part of the Github repository. The class also has methods to get column headings and object property names.

在陷入创建表之前,我需要简要描述数据源。 在现实世界中,您可能会例如从根据从REST API获得的JSON解析的数据结构填充表。 对于这个演示中,我有硬编码的数据到一个类的elements.js一个静态方法,它是Github上库的一部分。 该类还具有获取列标题和对象属性名称的方法。

This is the beginning of the element data just so you can see what it looks like.

这只是元素数据的开始,因此您可以看到它的外观。

Now let’s start looking at the code in creatingtables.js.

现在,让我们开始寻找在creatingtables.js代码。

Here we call one of the three functions to create and populate our table. You can of course comment/uncomment the function calls to run the one you want.

在这里,我们调用三个函数之一来创建和填充表。 您当然可以注释/取消注释该函数调用以运行所需的函数。

Below is the first of these functions.

以下是这些功能中的第一个。

The overall structure of the three functions is the same:

这三个功能的总体结构是相同的:

  • Grab the data抓取数据
  • Create a table建立表格
  • Add a caption添加标题
  • Add column headings添加列标题
  • Insert the data插入数据
  • Insert the table into the empty div in creatinghtmltables.htm将表格插入createhtmltables.htm中的空div中

In this first one we create a variable called tablehtml to hold the table as a string, and it is initialized with the opening table tag and caption.

在第一个tablehtml ,我们创建一个名为tablehtml的变量以将表保存为字符串,并使用开头的表标签和标题对其进行初始化。

Next we add a row and iterate the headings, adding a cell for each, before closing the row tag.

接下来,在关闭row标签之前,添加一行并重复标题,为每个标题添加一个单元格。

After that we iterate the array of elements, adding a row for each and then iterating the properties of each element object, adding cells as we go along.

之后,我们迭代元素的数组,为每个元素添加一行,然后迭代每个元素对象的属性,并在过程中添加单元格。

Finally we just need to close the table and set it as the innerHTML of the empty div.

最后,我们只需要关闭表并将其设置为空div的innerHTML

The advantage of this approach is that we are only hitting the DOM once at the end when setting innerHTML. Of course all the elements still need to be added to the DOM but this is done at a lower level by the JavaScript engine rather than our JS function calls. In the second function below we are calling DOM methods several hundred times, even for this fairly modestly sized data set.

这种方法的优点是,在设置innerHTML时,最后只需要打一次DOM。 当然,所有元素仍然需要添加到DOM中,但这是由JavaScript引擎而不是我们的JS函数调用在较低级别完成的。 在下面的第二个函数中,即使对于这个大小适中的数据集,我们也要调用DOM方法数百次。

The disadvantage is that we are hard-coding HTML into JavaScript. It’s pretty difficult to avoid this completely but extensive HTML in JavaScript is fiddly to write and maintain and violates any separation of concerns dogma you subscribe to.

缺点是我们将HTML硬编码为JavaScript。 完全避免这种情况非常困难,但是JavaScript中大量HTML的编写和维护很奇怪,并且违反了您所订阅的关注原则的任何分离。

Let’s move on to standard DOM methods.

让我们继续进行标准的DOM方法。

The overall structure is pretty much the same here, but this function uses createElement and createTextNode for the table, caption, rows and cells, which are then added to their respective parents with appendChild.

此处的总体结构几乎相同,但是此函数对表,标题,行和单元格使用createElementcreateTextNode ,然后使用appendChild将它们添加到其各自的父级中。

The advantage is that we are using “official” front-door methods to manipulate the DOM which is more robust. If we call, for example, document.createElement(“tr”) then we know that we will get a <tr> without worrying about typos or having to remember to add </tr> at the end.

好处是我们使用“官方”前门方法来操作DOM,这更加健壮。 例如,如果我们调用document.createElement(“tr”)则说明我们将得到<tr>而不用担心拼写错误或不必记得最后添加</tr>

The disadvantages are firstly, as I mentioned above, a large number of calls to the various DOM methods, nearly 500 in this fairly small table, and secondly this code is much longer than that in the next function listed below.

缺点是,首先,如上所述,大量调用各种DOM方法,在这个相当小的表中将近500个调用,其次,此代码比下面列出的下一个函数的代码长得多。

Finally let’s look at some methods provided by table elements.

最后,让我们看一下表元素提供的一些方法。

The same overall structure here but as you can see the code is much more compact.

此处的总体结构相同,但是如您所见,代码更加紧凑。

We still need document.createElement(“table”) to create a table but after that we can use methods and properties of the table or its child elements to create the caption, rows and cells.

我们仍然需要document.createElement(“table”)来创建表,但是此后,我们可以使用表或其子元素的方法和属性来创建标题,行和单元格。

Note that insertRow and insertCell take an index argument but you can use -1 to insert the row or cell at the end as I have done here.

请注意, insertRowinsertCell使用索引参数,但是您可以使用-1在末尾插入行或单元格,就像我在这里所做的那样。

One slight irritation is that you cannot directly create a <th> as insertCell always gives you a <td>. I have got round this by overwriting the new cell’s outerHTML.

有点恼人的是您不能直接创建<th>因为insertCell总是给您一个<td> 。 我已经通过覆盖新单元格的outerHTML

When inserting cells there are two ways to set the text, setting innerHTML or creating/appending a text node. I couldn’t make up my mind which I prefer: the first is more compact, the second more inkeeping with the spirit of this function’s approach. Take your pick.

插入单元格时,有两种方法来设置文本,设置innerHTML或创建/附加文本节点。 我无法下定决心,我更喜欢:第一个更加紧凑,第二个更加符合此函数方法的精神。 随便你吧。

The same advantages/disadvantages apply: code which is easier to write and maintain versus large numbers of DOM manipulation calls.

优点/缺点相同:与大量DOM操作调用相比,此代码更易于编写和维护。

试试看 (Try it Out)

If you want to see the results open creatinghtmltables.htm in your browser and run one function at a time by uncommenting the function calls in window.onload. Of course the end result is identical for all three.

如果要查看结果,请在浏览器中打开creationhtmltables.htm并通过取消注释window.onload的函数调用来一次运行一个函数。 当然,三者的最终结果是相同的。

结论 (Conclusion)

So, which to use? There is no definitive answer but I cannot see any advantage in the second option, createElement, createTextNode and appendChild as we have more specialized methods available.

那么,该使用哪个呢? 没有明确的答案,但是我看不到第二个选项createElementcreateTextNodeappendChild任何优势,因为我们有更多可用的专用方法。

If you have a simple but large data set then building a string is efficient if you don’t mind coding all the opening and closing tags and their content, and risking having to untangle the code if the data structure or requirements change. If you have small amounts of data and prefer slick and elegant code then go with option three, createCaption, insertRow and insertCell.

如果您有一个简单但庞大的数据集,那么如果您不介意对所有的开始和结束标签及其内容进行编码,并且如果数据结构或需求发生变化,则有可能需要解开代码,则构建一个字符串是有效的。 如果您的数据insertCell ,并且喜欢简洁流畅的代码,请选择选项三: createCaptioninsertRowinsertCell

Also please note that createCaption, insertRow and insertCell are only a few of the table-specific methods and I will look at the others in a future article.

还请注意, createCaptioninsertRowinsertCell只是一些表特定的方法,我将在以后的文章中介绍其他方法。

翻译自: https://medium.com/javascript-in-plain-english/building-html-tables-with-javascript-15c79a0055ff

javascript做表


http://www.taodudu.cc/news/show-7043453.html

相关文章:

  • 《Code:The Hidden Language of Computer Hardware and Software》 读书笔记
  • Yolact
  • 如何进行视频压缩?一步一步教会你操作
  • 计算机视听觉机理和方法,视听觉信息的认知计算
  • 听觉器官及机理
  • 听觉与感知的一些基本概念
  • 【智能语音】神经网络如何模拟人耳听觉机制?
  • 计算机视听觉机理和方法,重大研究计划“视听觉信息的认知计算” - 基金申请 - 小木虫 - 学术 科研 互动社区...
  • 【学习笔记】计算机听觉
  • 听觉神经网络(二):听觉通路
  • 机器人听觉处理浅析
  • 程序员2014年展望未来的八个小提示
  • 如何搭建一个完整的交易框架
  • 中e管家教会你如何利用闲钱做理财
  • win10 任务管理器没了
  • Win11怎么打开任务管理器
  • java checkStyle ‘cast‘ is not followed by whitespace.
  • 解决Element type “web-app“ must be followed by either attribute specifications, “>“ or “/>“.报错问题
  • stm32中c语言换行符error——expect a declaration warning——“\“followed by white space is not a line splic
  • 十四、报错:configparser.InterpolationSyntaxError: ‘%‘ must be followed by ‘%‘ or ‘(‘, found: “%)‘] 的解决
  • 编译时出现的(error C2632: 'long' followed by 'long' is illegal )非法定义的问题
  • 解决Element type “http:“ must be followed by either attribute specifications, “>“ or “/>“.
  • The link you followed has expired(您点击的链接已过期)
  • Feed-Forward Layers
  • iOS-An Apple ID verification code is required to sign in. Type your password followed by the verific
  • windows cmake调试Google test 报错:VERSION keyword not followed by a value...
  • RapidJSON报错: The document root must not be followed by other values.
  • docker中使用$PWD: 提示 ‘:‘ was not followed by a valid variable name character. 解决方案
  • ConfigParser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found: %' 解决方案
  • as follows ,as follow following

javascript做表_使用JavaScript构建HTML表相关推荐

  1. python 词汇表_使用Counter构建词汇表

    这里只记录两种情况: 1 数据集是一段连续的文本,所有词汇放在一个list中(一维的) text: 此时Counter(text),text可以是一个list,统计该list中所有元素出现的次数并返回 ...

  2. javascript做游戏_我用JavaScript构建了一个角色扮演游戏。 你也可以 这是如何做。...

    javascript做游戏 by Robert Skalko 罗伯特·斯科尔科(Robert Skalko) 我用JavaScript构建了一个角色扮演游戏. 你也可以 这是如何做. (I built ...

  3. javascript单引号_避免JavaScript单文化

    javascript单引号 本文由Tom Greco , Dan Prince和Mallory van Achterberg进行了同行评审. 感谢所有SitePoint的同行评审员使SitePoint ...

  4. javascript中对象_了解JavaScript中的承诺

    javascript中对象 我向您承诺,到本文结束时,您将更好地了解JavaScript. 我与JavaScript有一种"爱与恨"的关系. 但是尽管如此,JavaScript一直 ...

  5. javascript经典实例_提升JavaScript变量的方法有哪些?

    程序中的变量无处不在.它们是始终相互交互的小数据和逻辑片段:并且此活动使应用程序存活. 在JavaScript中,使用变量的一个重要方面是提升,它定义了何时可以访问变量.如果您正在寻找有关这方面的详细 ...

  6. javascript 高级程序设计_所以 JavaScript 到底是什么?我居然懵了????

    前言 引用<JavaScript 高级程序设计第四版>中说的话 --"从简单的输入验证脚本到强大的编程语言,JavaScript 的崛起没有任何人预测到.它很简单,学会用只要几分 ...

  7. excel链接隐藏工作表_自动隐藏Excel工作表

    excel链接隐藏工作表 When you build a workbook for other people to use, there might be worksheets that can s ...

  8. excel数据透视表_来自多个工作表的Excel数据透视表更新

    excel数据透视表 If you have similar data on two or more worksheets, you might want to combine that data i ...

  9. mmse评估量表_简易精神状态评价量表(mmse量表) 打印版.doc

    简易精神状态评价量表(mmse量表)15016 简易精神状态评价量表(MMSE) 项目 积分 定向力 (10分) 1.今年是哪一年 现在是什么季节? 现在是几月份? 今天是几号? 今天是星期几? 1 ...

最新文章

  1. 你能找到心仪的妹子吗?- 时间复杂度进阶
  2. [笔记]filter,空字符,0,None都是False应用
  3. html+店铺+可视化编辑器,开源在线可视化HTML编辑器 – xhEditor | 骤雨打新荷
  4. 用户认证-什么是认证
  5. C#:委托基础与事件
  6. Android 的一点总结
  7. 多模态融合算法——Multimodal Compact Bilinear Pooling
  8. maya显示已安装_【3D建模】Maya操作秘籍83招(一)
  9. 《代码敲不队》第八次团队作业:Alpha冲刺 第五天
  10. 基于STM32的(NB-IOT(BC26))温湿度监测系统
  11. vue.js中在js获取指定日期到现在时间的天数
  12. 合唱队形——线性dp
  13. Excel图表5——旋风图(对称条形图)
  14. 苹果录屏精灵_最新2018苹果APP排行榜,这四款没上榜真是太可惜了!
  15. ffmpeg 转换flv压缩大小_视频压缩工具ffmpeg的使用
  16. IBM罗睿兰的“告别信”
  17. spleeter音乐人声分离、5种架子鼓钢琴声音分离的高质量模型运行超详细教程windows+ubuntu18.04
  18. python函数第六关
  19. Java词向量比较字符串相似度_Sequence Model-week2编程题1-词向量的操作【余弦相似度 词类比 除偏词向量】...
  20. oracle系统表空间和自定义表空间

热门文章

  1. 基于Django和翻译API实现web版的中英文对照翻译(一)
  2. 学习安装libigl库
  3. 氢键金属有机骨架MOF修饰5-硝基间苯二甲酸/HOF-6/HOF-1111 的制备过程
  4. 系统运维安全管理办法_运维安全管理系统-堡垒机
  5. LabVIEW浮点型和双精度数据类型之间的精度差异是什么 为什么 在LabVIEW 中, 浮点 数 会 失去 精度?
  6. asdasdasda
  7. 关系抽取(RE)的损失函数
  8. 求三角形面积c 语言,C语言求三角形面积
  9. dSploit—Android网络***套件测试小记(含视频)
  10. 北京党建展馆vr全景制作优点有哪些