使用 javascript 在 HTML table 中插入新列

Inserting a new column in a HTML table using javascript

我正在尝试向动态创建的 table 添加一个按钮,但我无法使用 insertCell() 方法跳过第一行(这些是 table headers).. 谁能告诉我哪里出错了。谢谢..

此外,任何有关改进此代码的帮助都将不胜感激,因为我才刚刚开始学习 JavaScript。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html">
  <title>Client Side Shopping Basket</title>
  <meta name="author" content="Justin">
  <link href="basket.css" rel="stylesheet" type="text/css" media="screen" />
</head>

<body>
<div id="container">
    <header id="title">
        <h1>Products</h1>
    </header>
    <div class="output">
        <table border="1" id="productTable">
            <tr>
                <th>Name</th>
                <th>Description</th>
                <th>Quantity</th>
                <th>Price</th>
                <th>Gender</th>
            </tr>
        </table>
    </div>
    <br /><br />
    <header id="title">
        <h1>Shopping Basket</h1>
    </header>
    <div id="basket">
        <table border="1">
            <tr class="netcost">
                <td class="light">Net Total:</td>
                <td colspan="2" class="light"></td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr class="totalcost">
                <td class="light">Total:</td>
                <td colspan="2">&nbsp;</td>
                <td colspan="2"><span class="thick">£225.45</span></td>
            </tr>
            <tr class="checkout">
                <td colspan="5" class="checkout"><button id="submitbtn">Checkout Now!</button></td>
            </tr>
            </tbody>
        </table>
    </div>
</div>
<p id="test"></p>

<script>
var productList = []; //where product objects are to be held
var basket = [];
var objectNames = [];
var obj;
//constructor
function Product(name, description, quantity, price, gender) 
{ 
    obj = this; // a reference to this object

    this.name = name;
    this.description = description;
    this.quantity = quantity;
    this.price = price.toFixed(2);
    this.gender = gender;
    this.getName = function() {
        return this.name
    };
    this.getPrice = function() {
        return '\u00A3' + this.price;
    };
};

//instantiate new products 
var shorts = new Product('Shorts', 'Stone Wash Demin Shorts', 20, 25.90, 'F');
var bag = new Product('Bag', 'Leather Shoulder Bag', 4, 50.45, 'F');
var blouse = new Product('Blouse', 'Vintage Blue Silk Polka Dot Blouse', 8, 45.99, 'F');
var boots = new Product('Boots', 'Soft Leather Brown Ankle Boots', 3, 65.35, 'F');
var belts = new Product('Belts', 'Woven Finish Fashion Belt', 15, 21.99, 'F');
var shirt = new Product('Shirt', 'Jacquard Pattern Wrangler Western Shirt', 19, 34.87, 'M');
var shoes = new Product('Shoes', 'Suede Ankle Boots', 6, 55.00, 'M');
var trousers = new Product('Trousers', 'Izod Peach Chinos', 23, 31.75, 'M');
var belt = new Product('Belt', 'Suede Casual Belt', 4, 22.98, 'M');
var hat = new Product('Hat', 'Trilby Style Brown Woven Fix', 2, 67.80, 'M');

//add objects to an array
productList.push(shorts, bag, blouse, boots, belts, shirt, shoes, trousers, belt, hat);

function appendRow(productTable) {
    var tbl = document.getElementById('productTable'); // reference to table
    var cellCount = tbl.rows[0].cells.length; // counts the cells in first row of table
    var row = tbl.insertRow(1); // inserts a row
    var counter;
    for (var counter=0; counter < countCells; ++counter) { // iterate through table headers 
    };
};
//print product list
function createTable(products) {   // passes in the product list

    var tbl = document.getElementById('productTable'); // reference to the table to add rows to

    for (var i=0; i < products.length; i++) { // index the productsList (iterate through 0-9)

        var myProduct = products[i]; // keep a reference to each individual product - shorts, bag, blouse, etc...
        var row = tbl.insertRow(tbl.rows.length); // create a row element to append cells to
        var myProperties = ['name', 'description', 'quantity', 'price', 'gender']; //store the property names of the products, references to the object data

        var objectName = products[i].name.toLowerCase(); //lower-case the name for object name
        objectNames[i] = objectName; // add them to an array ????

        for (var j=0; j < myProperties.length; j++) // for each property in myProperties [0-4]
        {   
            var cell = document.createElement('td'); //create table cell element
            var data = myProduct[myProperties[j]]; // store property values of products
            var node = document.createTextNode(data); //add the data to a text node 
            cell.appendChild(node); // append text node to table cell
            row.appendChild(cell); // add to end of the row
        }

        var newCell = tbl.rows[i].insertCell(tbl.rows[i].cells.length); // insert new cell at end of each row

        function createBtn() {
        //create button
            var btn = document.createElement('input'); 
            btn.type = 'button';
            btn.value = 'Add';
            btn.name = objectNames[i];
            btn.onclick = function() {alert(objectNames);};
            return btn;
        };

        newCell.appendChild(createBtn()); // add button to cell
        tbl.appendChild(row); // add new row to table
    }
};

createTable(productList); // pass in productList Array

</script>
</body>
</html>

这是一个简单的解决方案,无需修改您的大部分代码...

更改创建 newCell 的方式(第 122 行)。替换为以下行:

    *var newCell = tbl.rows[i+1].insertCell(tbl.rows[i+1].cells.length); // insert new cell at end of each row*