處理網頁中表格內容

  • *     通過<table></table>標記中的id得到表格對象,或通過innerHTML插入表格對象。

    <li>*     通過表格對象的insertRow方法在表格中插入行。

    <li>*     通過行對象的insertCell方法在行中插入表格元素。

    <li>*     通過表格元素對象的innerHTML方法添加表格元素中的內容。

    <li>*     通過行對象的deleteCell方法刪除行中的表格元素。

    <li>*     通過表格對象的deleteRow方法刪除表格中的行。

    <html>

    <head>

          <meta http-equiv="Content-Type" content="text/html; charset=gb2312">

          <title>處理網頁中表格內容</title>

          <script language="JavaScript">

          <!--

                function addRow()              //添加行

                {

                     var tableObj = document.getElementById("mainTb");  //獲取表格相關屬性

                     //設置行、名稱、單位、按鈕等相關變量

                     var newRowObj = tableObj.insertRow(tableObj.rows.length);

                     var newNameCell = newRowObj.insertCell(newRowObj.cells.length);

                     var newCompanyCell = newRowObj.insertCell(newRowObj.cells.length);

                     var newButtonCell = newRowObj.insertCell(newRowObj.cells.length);

                     //添加“姓名”表元

                     newNameCell.innerHTML = document.getElementById("newName").value;

                     //添加“單位”表元

                     newCompanyCell.innerHTML = document.getElementById("newCompany").value;

                     //添加“刪除”表元

                     newButtonCell.innerHTML = '<input type="button" value="刪除" οnclick="deleteRow('+(tableObj.rows.length-1)+')">';

                }

                function deleteRow(index)      //刪除行

                {

                      var tableObj = document.getElementById("mainTb");  //獲取表格相關屬性

                      tableObj.deleteRow(index);       //刪除指定行

                }

          //-->

          </script>

    </head>

    <body  bgcolor="#FFC0C0" style="margin:40px">

          <h2>處理網頁中的表格內容</h2><hr><br>

          <table id="mainTb" border="1">

                <tr><th width="80">姓名</th><th width="250">單位</th></tr>

                <tr id="row0"><td>張辰剛</td><td>北京華夏食品有限公司</td>

                         <td><input type="button" value="刪除" οnclick="deleteRow(0)"></td></tr>

                <tr id="row1"><td>郭興旺</td><td>廣州天河文化傳播公司</td>

                         <td><input type="button" value="刪除"οnclick="deleteRow(1)"></td></tr>

          </table><br>

          <div><hr>

          <span id="new">

               姓名:<input type="text" name="newName" id="newName"><br>

               單位:<input type="text" id="newCompany">&nbsp;

               <input type="button" value="添加" οnclick="addRow()">

          </span>

          </div>

    </body>

    </html>
  • 發表評論
    所有評論
    還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
    相關文章