HTML表格用javascript添加列

我显然对 JS 很陌生。我需要解决无法更改 HTML 和 CSS 文件的问题。从 HTML 文件我应该:


添加标题为“Sum”的列。(已经这样做了)在底部添加一行,div id 为“sumrow”。(也是这样做的)在最后添加一个按钮。(这样做)单击按钮时将“价格和金额”列中的总计添加到“总和”列中(这是我迷路的地方)


就像我说的,我无法更改 HTML 和 CSS 文件中的任何内容。


    // Create a newelement and store it in a variable 

    var newEl = document.createElement('th');

    //Create a text node and store it in a variable 

    var newText = document.createTextNode('Summa');

    //Attach the newtext node to the newelement 

    newEl.appendChild(newText);

    //Find the position where the new element should be added 

    var position = document.getElementsByTagName('tr')[0];

    //Insert the newelement into its position 

    position.appendChild(newEl);

    

    

    

    

    

    // Find a <table> element with id="myTable":

    var table = document.getElementById("pricetable");

    

    // Create an empty <tr> element and add it to the 1st position of the table:

    var row = table.insertRow(-1);

    

    // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:

    var cell1 = row.insertCell(0);

    var cell2 = row.insertCell(1);

    var cell3 = row.insertCell(2);

    var cell4 = row.insertCell(3);

    var cell5 = row.insertCell(4);

    var cell6 = row.insertCell(5);

    

    // Add some text to the new cells:

    cell1.innerHTML = "";

    cell2.innerHTML = "";

    cell3.innerHTML = "";

    cell4.innerHTML = sumVal;

    cell5.innerHTML = "";

    cell6.innerHTML = "";

    

    //Puts divid sumrow

    row.setAttribute("id", "sumrow");

    

    var table = document.getElementById("pricetable"), sumVal = 0;

    

    for(var i = 1; i < table.rows.length; i++)

    {

        sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);

    }

    

    //Creates button

    

    var button = document.createElement("button");

    button.innerHTML = "Beräkna pris";

    

    // 2. Append somewhere

    var body = document.getElementsByTagName("tbody")[0];

    body.appendChild(button);

    

撒科打诨
浏览 248回答 2
2回答

江户川乱折腾

button.addEventListener("click", medelVarde, true);button.addEventListener("click", raknaUtMedelvarde, true);&nbsp;对于按钮点击事件监听器,您不必添加该medelVarde函数。另外,说到那个功能,我不太确定那里发生了什么。你想把价格和数量相乘吗?如果是这样,您可以只获取价格单元格的文本并将其乘以输入的金额值(在乘法之前将值转换为数字)。const [,,, priceCell, amountCell, sumCell] = row.querySelectorAll('td');const price = Number(priceCell.innerText);const amount = Number(amountCell.querySelector('input').value);const sum = price * amount;这[,,, priceCell, amountCell, sumCell]只是从行中获取所需单元格的简写方式(解构赋值。querySelectorAll返回一个 NodeList,您可以在其中按索引获取元素。function setUp() {&nbsp; // Set up table.&nbsp; const table = document.getElementById('pricetable');&nbsp; const headerRow = table.querySelector('thead tr');&nbsp; const sumHeader = headerRow.insertCell();&nbsp; const tbody = table.querySelector('tbody');&nbsp; const sumTotalRow = tbody.insertRow();&nbsp; const sumTotalCell = sumTotalRow.insertCell();&nbsp; sumHeader.innerText = 'Summa';&nbsp; sumTotalCell.colSpan = '5';&nbsp; sumTotalCell.innerText = 'Total';&nbsp; tbody.querySelectorAll('tr').forEach(row => row.insertCell());&nbsp;&nbsp;&nbsp; // Set up button.&nbsp; const btn = document.createElement('button');&nbsp; btn.innerText = 'Beräkna pris';&nbsp;&nbsp;&nbsp; btn.addEventListener('click', () => {&nbsp; &nbsp; let total = 0;&nbsp;&nbsp;&nbsp; &nbsp; tbody.querySelectorAll('tr').forEach((row, i, arr) => {&nbsp; &nbsp; &nbsp; if (i < arr.length - 1) {&nbsp; &nbsp; &nbsp; &nbsp; const [,,, priceCell, amountCell, sumCell] = row.querySelectorAll('td');&nbsp; &nbsp; &nbsp; &nbsp; const price = Number(priceCell.innerText);&nbsp; &nbsp; &nbsp; &nbsp; const amount = Number(amountCell.querySelector('input').value);&nbsp; &nbsp; &nbsp; &nbsp; const sum = price * amount;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; sumCell.innerText = sum;&nbsp; &nbsp; &nbsp; &nbsp; total += sum;&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; const totalCell = row.querySelector('td:last-child');&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; totalCell.innerText = total;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; });&nbsp;&nbsp;&nbsp; document.body.appendChild(btn);}setUp();

犯罪嫌疑人X

首先,我建议将逻辑包装到函数中,例如appendRow() {&nbsp; &nbsp; //put append row logic here}现在让我们继续你的问题,附加一列比附加一行更像是一个技巧。您可能已经注意到 DOM 结构有点复杂。因此,对于一行,您可以正确地向您的 tbody 添加一个节点。对于列,我们需要了解如何创建单元格以及如何向 thead 添加条目。我们将使用insertCell()方法插入单元格,对于行不通的单元格,因此我们需要使用 createElement() 添加 th 并使用 appendChild() 追加它function appendColumn() {&nbsp; &nbsp; &nbsp; &nbsp; // insertCell doesn't work for <th>-Nodes :-(&nbsp; &nbsp; &nbsp; &nbsp; var tableHeadRef = document.getElementById('pricetable').tHead; // table reference&nbsp; &nbsp; &nbsp; &nbsp; var newTh = document.createElement('th');&nbsp; &nbsp; &nbsp; &nbsp; tableHeadRef.rows[0].appendChild(newTh); // inser new th in node in the first row of thead&nbsp; &nbsp; &nbsp; &nbsp; newTh.innerHTML = 'thead title';&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // open loop for each row in tbody and append cell at the end&nbsp; &nbsp; &nbsp; &nbsp; var tableBodyRef = document.getElementById('pricetable').tBodies[0];&nbsp; &nbsp; &nbsp; &nbsp; for (var i = 0; i < tableBodyRef.rows.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var newCell = tableBodyRef.rows[i].insertCell(-1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newCell.innerHTML = 'cell text'&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }编辑:要总结 col 中的值,可以使用相同的方法。我分解了节点以便更好地理解。如果您的表数据包含带有isNaN() 的数字,您可能还想添加一个检查。function sumColumn(tableId, columnIndex) {&nbsp; &nbsp; var tableBodyRef = document.getElementById(tableId).tBodies[0];&nbsp; &nbsp; var sum = 0; // Initialize sum counter with 0&nbsp; &nbsp; for (var i = 0; i < tableBodyRef.rows.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var currentRow = tableBodyRef.rows[i]; //access current row&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var currentCell = currentRow.cells[columnIndex]; // look for the right column&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var currentData = currentCell.innerHTML; // grab cells content&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var sum += parseFloat(currentData); // parse content and add to sum&nbsp; &nbsp; }&nbsp; &nbsp; return sum;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript