body onload()事件和table insertRow()、tr insertCell()

onload事件:

定义和用法:

onload 事件会在页面或图像加载完成后立即发生。

onload 通常用于 <body> 元素,在页面完全载入后(包括图片、css文件等等。)执行脚本代码。

语法:

在HTML中:<body onload="SomeJavaScriptCode">

在JavaScropt中:window.onload=function(){SomeJavaScriptCode};

SomeJavaScriptCode必需。规定该事件发生时执行的 JavaScript。(执行代码)

实例:<body onload="myFunction()">

table insertRow()函数方法

定义和用法:insertRow() 方法用于在表格中的指定位置插入一个新行。

语法:tableObject.insertRow(index);index:指定插入新行的位置 (以 0 开始)。

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title></title> 
<script>
function displayResult(){
    var table=document.getElementById("myTable");
    var row=table.insertRow(0);
    var cell1=row.insertCell(0);
    var cell2=row.insertCell(1);
    cell1.innerHTML="New";
    cell2.innerHTML="New";
}
</script>
</head>
<body>

<table id="myTable" border="1">
    <tr>
        <td>cell 1</td>
        <td>cell 2</td>
    </tr>
    <tr>
        <td>cell 3</td>
        <td>cell 4</td>
    </tr>
</table>
<br>
<button type="button" onclick="displayResult()">插入新行</button>

</body>
</html>

tr insertCell()函数方法

定义和用法:insertCell() 方法用于在 HTML 表的一行的指定位置插入一个空的 <td> 元素。

语法:trObject.insertCell(index);index:该方法将创建一个新的 <td> 元素,把它插入行中指定的位置。新单元格将被插入当前位于 index 指定位置的表元之前。如果 index 等于行中的单元格数,则新单元格被附加在行的末尾。

实例:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title></title> 
<script>
function displayResult(){
    var firstRow=document.getElementById("myTable").rows[0];
    var x=firstRow.insertCell(-1);
    x.innerHTML="New cell"
}
</script>
</head>
<body>

<table id="myTable" border="1">
    <tr>
        <td>First cell</td>
        <td>Second cell</td>
        <td>Third cell</td>
    </tr>
</table>
<br>
<button type="button" onclick="displayResult()">插入单元格</button>

</body>
</html>

猜你喜欢

转载自www.cnblogs.com/xiaochen-cmd-97/p/11298405.html
今日推荐