`
format_me
  • 浏览: 31063 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

javascript 动态添加表格行

阅读更多

介绍如何使用javascript动态添加表格行,并对其中的方法做详细的说明

 

动态添加表格行  

文/Ray

 表格部分代码如下:

<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 newTd 1 = newTr.insertCell();

// 设置列内容和属性

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

newTd2.innerText= ' 新加行 ';

}

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

1 inserRow() 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(" 这是新添加的行 ");

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

 

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

 

转载出处:http://www.cnblogs.com/rhodamine/archive/2006/07/18/453430.html

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics