当前位置: 首页 > 图文教程 > 网络编程 > Javascript > javascript 动态添加表格行

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 javascript 动态添加表格行


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 257 ::
收藏到网摘: n/a

表格部分代码如下:

<table id="testTbl" border=1>

<tr id="tr1">

<td width=6%><input type=checkbox id="box1"></td>

<td id="b">第一行</td>

</tr>

<tr id="tr2">

<td width=6%><input type=checkbox id="box2"></td>

<td id="b">第二行</td>

</tr>

<tr bgcolor=#0000FF>

<td width=6%><input type=checkbox id="box3"></td>

<td>第三行</td>

</tr>

</table>

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

function addRow(){

//添加一行

var newTr = testTbl.insertRow();

//添加两列

var newTd0 = newTr.insertCell();

var newTd1 = newTr.insertCell();

//设置列内容和属性

newTd0.innerHTML = '<input type=checkbox id="box4">';

newTd2.innerText= '新加行';

}

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

1inserRow()insertCell()函数

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

insertRow(index)

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

insertCell()insertRow的用法相同。

2、动态设置属性和事件

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

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

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

newTr.bgColor = 'red';

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

比如,我要让点击新加行的时候执行一个自己定义的函数 newClick,newClick行数如下:

function newClick(){

alert("这是新添加的行");

onclick事件设置这个函数的代码如下:

newTr.onclick = newClick;

这里需要主义的是,=后面的部分必须是函数名,而且不能带引号,

newTr.onclick = newClick();

newTr.onclick = 'newClick';

newTr.onclick = "newClick";

上面的写法都是错误的。

为什么,其实知道为什么没有什么意思,知道怎么用就OK了,如果不想知道,可以跳过下面这一段。

实际上这个=后面的newClick是指向自己定义的newClick函数的指针,javascript里面函数名就是指向函数的指针,加了引号括号什么的浏览器就找不到那个函数了。

下面的写法,也是正确的

newTr.onclick = function newClick(){

alert("这是新添加的行");

这个使用函数名实际上是一样的

设置其他的事件用法相同。