Home Web Front-end JS Tutorial JavaScript study notes (2) Use DOM to write browser-compatible Table operations

JavaScript study notes (2) Use DOM to write browser-compatible Table operations

Dec 19, 2016 pm 05:31 PM

If you want to dynamically operate the Table, you must be familiar with the DOM. If you want to achieve browser compatibility, you must be familiar with the W3C standards and the characteristics of each browser in table operations. Table is the best choice for data display today. DOM has specially added some features and methods for Table, which helps us write simpler and more efficient programs.

Note: The program in this article was tested under IE7 and Firefox3.

Procedure 1: Dynamically create a table

1 ;            return;

13 ; ,"tableStyle");
18 tableNode .setAttribute("border",1);             for(var j = 0; j < cellCount; j++){
23 var newCell = newRow.insertCell(0);
24 newCell.innerHTML = Number(i+1) + "×" + Number(j+1);
25            }
26}
27 document.body.appendchild (tablenode);
28}
This function is very simple: 14 lines use the document.createElement () method to create a Table label. At this step, we have not encountered the place where you need to pay attention, because Most browsers support this method. In lines 16-18, we use the setAttribute() method to add attributes to the newly created table tag. Although these lines of code can be parsed by IE and FF, the book "JavaScript Advanced Programming" points out:
IE is using the setAttribute() method. There is a big problem, when you use it, changes will not always be reflected correctly. If you plan to support IE, it is best to use attributes whenever possible. What the master says always makes sense, so we can use attributes instead of methods. Fortunately, FireFox also provides support for attributes, so we can modify the program as follows:
1 tableNode.id = "tableNode";
2 tableNode.className = "tableStyle";
3 tableNode.border = "1"; The only thing to note is that when setting the class of the table, className must be used.
The insertRow() used in line 21 and the insertCell() used in line 23 are both special APIs provided by DOM for Table. The corresponding methods are deleteRow() and deleteCell(). When using these two methods, we should pay close attention to them. : IE provides the default parameter -1 for both methods, but FireFox does not provide parameters for them, so if there are no parameters, it can run normally under IE, but not under FireFox. So we should take care to always provide parameters to these two methods. In layman's terms, the meaning of the parameters of these two functions can be explained like this:
0: Put the new row on top of the existing row-------Always set the latest row index (rowIndex) to 0
-1: Place the newly created row below the existing row -------The row index is incremented, starting from 0
You can also set this parameter manually, but when the set parameter is greater than the row index of the current table + 1, the program will Report an error. insertCell() has similar meaning, no need to repeat!

Program 2: Insert new lines before and after the specified line

1

9                                                 alert("Look The table to be operated is not reached");
10                                                                                                                                                        //Find the specified row
14 through the row index if( Number(indexOfRow - 1) <= tableNode.rows.length){
15                       var tableRow = tableNode.rows[indexOfRow-1]; 
16                       var tableRow = tableNode.rows[tableNode.rows.length- 1 ]; //Insert a new line before the specified line
22 If(position == 1 ){
23                  tableRow.parentNode.insertBefore(newRow,tableRow);                   tableRow.parentNode.insertBefore(newRow,tableRow.nextSibling); 27
The rows used in line 15 of the program means that all rows in the table are returned an array, corresponding to cells: an array containing all cells in the table. Since it is an array containing all rows, we can naturally use the array index to get the value we want. The cloneNode() method used in line 20 is one of my favorite DOM methods. It allows us to target a specific HTML element. Perform deep (parameter is true) or shallow (parameter is false) copy. The so-called deep copy means returning a copy of the current element, which has the same special name as the original element. When we need to create a new element that is the same as an existing element (such as multiple file uploads), this method can help us save a lot of code. The so-called shallow copy means that only the skeleton of the element is copied without copying the specific name of the element. The meaning is difficult to express. You can set the parameters of the cloneNode() method of the above program to false to observe its effect.
The insertBefore() method used in line 23 is also very simple: insert the specified element in front of the current element. I often see people on the Internet saying why W3C doesn’t have insertAfter(). In fact, we just need to think about it in a different way. If the specified element is inserted in front of the next element of the current element, then the insertAfter() method will be implemented, hehe!

Program 3: Delete the specified row

1 /**
2                                                          */
5 function deleteTheRow(deleteRowIndex){
6 var tableNode = document.getElementById("tableNode");
7      var rowCount = tableNode.rows .length;
8
9 if(isNaN(deleteRowIndex) || parseInt(deleteRowIndex) < 1 || parseInt(deleteRowIndex) > Number(rowCount)){
10 alert(" Please enter a number greater than 0 and less than "+Number (rowCount)+"Number")
11                                                                                                                                                                 Easy to say, the main method used is deleteRow() , but be careful: the parameters passed in cannot be greater than the number of rows in the table, otherwise an error will be reported!

Program 4: Delete the specified cell

1 /**
2                                                                          */

6 function deleteTheCell(indexOfRow,indexOfCell){

7 var tableNode = document.getElementById("tableNode");

8          var rowNode = tableNode.rows[Number(indexOfRow - 1)];

9     rowNode.deleteCell(Number(indexOfCell-1));
10   } Find the cell to be deleted using the provided row index and column index, and then call the deleteCell() method , and then the code to delete the specified column is similar to this. It is nothing more than looping through each row of the table, finding the specified column, and then deleting it.

The above are JavaScript study notes (2) using DOM to write browser-compatible Table operations. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles