javascript做表_使用JavaScript构建HTML表

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)。

Image for post

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.htm

    creationtables.htm
  • creatingtables.js

    creationtables.js
  • elements.js

    elements.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做表

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值