亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

HTML表格用javascript添加列

HTML表格用javascript添加列

撒科打諢 2023-03-24 16:33:47
我顯然對 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);    
查看完整描述

2 回答

?
江戶川亂折騰

TA貢獻1851條經驗 獲得超5個贊

button.addEventListener("click", medelVarde, true);

button.addEventListener("click", raknaUtMedelvarde, true); 

對于按鈕點擊事件監聽器,您不必添加該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() {

  // Set up table.

  const table = document.getElementById('pricetable');

  const headerRow = table.querySelector('thead tr');

  const sumHeader = headerRow.insertCell();

  const tbody = table.querySelector('tbody');

  const sumTotalRow = tbody.insertRow();

  const sumTotalCell = sumTotalRow.insertCell();


  sumHeader.innerText = 'Summa';

  sumTotalCell.colSpan = '5';

  sumTotalCell.innerText = 'Total';


  tbody.querySelectorAll('tr').forEach(row => row.insertCell());

  

  // Set up button.

  const btn = document.createElement('button');


  btn.innerText = 'Ber?kna pris';

  

  btn.addEventListener('click', () => {

    let total = 0;

  

    tbody.querySelectorAll('tr').forEach((row, i, arr) => {

      if (i < arr.length - 1) {

        const [,,, priceCell, amountCell, sumCell] = row.querySelectorAll('td');

        const price = Number(priceCell.innerText);

        const amount = Number(amountCell.querySelector('input').value);

        const sum = price * amount;

        

        sumCell.innerText = sum;

        total += sum;

      } else {

        const totalCell = row.querySelector('td:last-child');

        

        totalCell.innerText = total;

      }

    });

  });

  

  document.body.appendChild(btn);

}


setUp();


查看完整回答
反對 回復 2023-03-24
?
犯罪嫌疑人X

TA貢獻2080條經驗 獲得超4個贊

首先,我建議將邏輯包裝到函數中,例如


appendRow() {

    //put append row logic here

}

現在讓我們繼續你的問題,附加一列比附加一行更像是一個技巧。您可能已經注意到 DOM 結構有點復雜。因此,對于一行,您可以正確地向您的 tbody 添加一個節點。對于列,我們需要了解如何創建單元格以及如何向 thead 添加條目。我們將使用insertCell()方法插入單元格,對于行不通的單元格,因此我們需要使用 createElement() 添加 th 并使用 appendChild() 追加它


function appendColumn() {

        // insertCell doesn't work for <th>-Nodes :-(

        var tableHeadRef = document.getElementById('pricetable').tHead; // table reference

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

        tableHeadRef.rows[0].appendChild(newTh); // inser new th in node in the first row of thead

        newTh.innerHTML = 'thead title';

        

        // open loop for each row in tbody and append cell at the end

        var tableBodyRef = document.getElementById('pricetable').tBodies[0];


        for (var i = 0; i < tableBodyRef.rows.length; i++) {

            var newCell = tableBodyRef.rows[i].insertCell(-1);

            newCell.innerHTML = 'cell text'

        }

    }

編輯:要總結 col 中的值,可以使用相同的方法。我分解了節點以便更好地理解。如果您的表數據包含帶有isNaN() 的數字,您可能還想添加一個檢查。


function sumColumn(tableId, columnIndex) {

    var tableBodyRef = document.getElementById(tableId).tBodies[0];

    var sum = 0; // Initialize sum counter with 0


    for (var i = 0; i < tableBodyRef.rows.length; i++) {

         var currentRow = tableBodyRef.rows[i]; //access current row

         var currentCell = currentRow.cells[columnIndex]; // look for the right column

         var currentData = currentCell.innerHTML; // grab cells content

         var sum += parseFloat(currentData); // parse content and add to sum

    }


    return sum;

}


查看完整回答
反對 回復 2023-03-24
  • 2 回答
  • 0 關注
  • 278 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號