javascript操作表格
利用js来动态创建表格有两种格式,appendChild()和insertRow、insertCell()。两种方式其实差不多,但第一种有可能在IE上有问题,所以推荐大家使用第二种了,直接说吧。
1、inserRow()和insertCell()函数
insertRow()函数可以带参数,形式如下:
insertRow(index):index从0开始
这个函数将新行添加到index的那一行前,比如insertRow(0),是将新行添加到第一行之前。默认的insertRow()函数相当于insertRow(-1),将新行添加到表的最后。一般我们在使用的时候都是:objTable.insertRow(objTable.rows.length).就是为表格objTable在最后新增一行。
insertCell()和insertRow的用法相同,这里就不再说了。
2、deleteRow()和deleteCell()方法
deleteRow()函数可以带参数,形式如下:deleteRow(index):index从0开始
和上面两个方法差不多的意思,就是删除指定位置的行和单元格。要传入的参数:Index是行在表格中的位置,可以下面的方法取得然后去删除:
var row=document.getElementById("行的Id");
var index=row.rowIndex;//有这个属性,嘿嘿
objTable.deleteRow(index);
在使用过程中我碰到的一个问题跟大家说一下,就是删除表格的行的时候,如果你删除了某一行,那么表格行数是马上就变化的,所以如果你要删除表格的所有行,下面的代码是错误的:
function clearRow(){
objTable= document.getElementById("myTable");
for( var i=1; i<objTable.rows.length ; i++ )
{
tblObj.deleteRow(i);
}
}
这段代码要删除原来的表格的表体,有两个问题。首先不能是deleteRow(i),应该是deleteRow(1)。因为在删除表格行的时候,表格的行数在变化,这就是问题的关键,rows.length总是在变小,删除的行数总是会比预想的要少一半,所以正确的删除表格的行的代码应该这样:
function clearRow(){
objTable= document.getElementById("myTable");
var length= objTable.rows.length ;
for( var i=1; i<length; i++ )
{
objTable.deleteRow(1);
}
}
3、动态设置单元格与行的属性
A、采用setAttribute()方法,格式如下:setAttribute(属性,属性值)
说明:这个方法几乎所有的DOM对象都可以使用,第一个参数是属性的名称,比如说:border,第二个就是你要为border设置的值了,比如:1
var objMyTable = document
相关文档:
Definition and Usage
定义与用法The constructor property is a reference to the function that created an object.
constructor属性是所建立对象的函数参考Syntax
语法object.constructor
Example 1
举例
In this example we will show how to use the constructor property:
在这个举例中我们将展示如何使用cons ......
IE可以调用:
<script type="text/javascript">
// 说明:获取页面上选中的文字
// 整理:http://www.CodeBit.cn
function getSelectedText() {
if (window.getSelection) {
// This technique is the most likel ......
网页常用小技巧
1. oncontextmenu="window.event.returnValue=false" 将彻底屏蔽鼠标右键
<table border oncontextmenu=return(false)><td>no</table> 可用于Table
2. <body onselectstart="return false"> 取消选取、防止复制
3. onpaste="return false" 不准粘贴
4. oncopy="return fa ......
判断浏览器类型
<SCRIPT language=javascript>
if(navigator.appVersion.indexOf("MSIE 6.") != -1 ){
window.location = "111.htm" ;
}
</SCRIPT>
按钮背景图片替换
<input type=button style="background-image:url(a.gif)" value=test onmouseover="this.style.backgroundImage='url(b.gif ......
<script>
function getCookieVal(offset) {
var endstr = document.cookie.indexOf(";",offset);
if(endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset,endstr));
}
function FixCookieDate(data) {
var ba ......