Home > Web Front-end > JS Tutorial > body text

javascript dynamically add table rows_JavaScript

WBOY
Release: 2016-05-16 19:29:23
Original
1391 people have browsed it

表格部分代码如下:

testTbl" border=1>

tr1">

tr2">

box1"> 第一行
box2"> 第二行
box3"> 第三行

动态添加表行的javascript函数如下:

function addRow(){

//添加一行

var newTr = testTbl.insertRow();

//添加两列

var newTd0 = newTr.insertCell();

var newTd1 = newTr.insertCell();

//设置列内容和属性

newTd0.innerHTML = 'box4">';

newTd2.innerText= '新加行';

}

就这么简单,做点详细的说明:

1inserRow()insertCell()函数

insertRow()函数可以带参数,形式如下:

insertRow(index)

这个函数将新行添加到index的那一行前,比如insertRow(0),是将新行添加到第一行之前。默认的insertRow()函数相当于insertRow(-1),将新行添加到表的最后。

insertCell()insertRow的用法相同。

2、动态设置属性和事件

上面行数中的innerHTML和innerText都是列的属性。

这个inner,就是“inner”到之间,innerText是添加到之间的文本,innerHTML是添加到之间的HTML代码(这个so简单,这个解释挺多余的)

设置其他属性也是用同样的方式,比如,设置行背景色

newTr.bgColor = 'red';

 

设置事件也一样,需要简单说明一点。

For example, I want to execute a self-defined function when clicking on a new row newClick, newClickThe number of rows is as follows:

function newClick(){

alert("This is a newly added line ");

The code to set this function for the onclick event is as follows:

newTr.onclick = newClick;

What needs to be done here is that the part after = must be the function name , and cannot be quoted,

newTr.onclick = newClick();

newTr.onclick = 'newClick';

newTr.onclick = "newClick";

The above writing is wrong.

Why, actually knowing why is meaningless. If you know how to use it, OK. If you don’t want to know, you can skip the following paragraph.

In fact, the newClick after = points to the self-defined newClickThe pointer to the function, the function name in javascript is the pointer to the function, and the browser will not be able to find the function if it is enclosed in quotation marks or brackets.

The following writing method is also correct

newTr.onclick = function newClick(){

alert("This is a newly added line ");

This is actually the same using the function name

Set other events in the same way.

Related labels:
source: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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!