首页 > 解决方案 > 在 html 表的 top-1 位置添加一行

问题描述

function addRowtoTop(first) {
// get input values
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var city = document.getElementById('city').value;
var country = document.getElementById('country').value;



// get the html table
// 0 = the first table
var table = document.getElementsByTagName('table')[0];

// add new empty row to the table
// 0 = in the top 
// table.rows.length = the end
// table.rows.length/2+1 = the center
var newRow = table.insertRow((table.rows.length / 0));'

我一直试图在 html 表的 top-1 位置添加一行,但不知道如何。通过这一行,var newRow = table.insertRow((table.rows.length / 0));我可以在顶部添加行,但它被添加到标题部分上方。提前致谢

标签: javascripthtml

解决方案


您需要将头部存储在一个变量中,然后是新行,然后取其余行,最后只需 table.innerHTML = newTable;

function addRow(){
        var table = document.querySelector('table');
        
        var Head = table.children[0].children[0].outerHTML;
        var newRow = '<tr><td>newShoes</td><td>Shoes</td><td>Shoes</td></tr>';
        var restOfTheTable = '';
        for(var i = 1; i<=table.children[0].children.length-1; i++){
            restOfTheTable += (table.children[0].children[i].outerHTML);
        }
        table.innerHTML = `${Head}${newRow}${restOfTheTable}`;
    }
<table>
        <tr>
            <td>name</td>
            <td>Price</td>
            <td>Location</td>
        </tr>
        <tr>
            <td>Shoes</td>
            <td>Shoes</td>
            <td>Shoes</td>
        </tr>
        <tr>
            <td>Shoes</td>
            <td>Shoes</td>
            <td>Shoes</td>
        </tr>
    </table>
<button onclick="addRow()">add row</button>


推荐阅读