簡體   English   中英

每次單擊表格單元格時,我都想控制台記錄每個單元格的值,每次單擊時? 什么是正確的稱呼?

[英]Every time I click the tables cell I want to console.log the value with each every cell, every time I click? what is the proper calling?

        <!-- The Row Number 0 -->

            <th>First Name</th>
            <th>Last Name</th>
            <th>Age</th>

        <!-- End Row Number 0 -->
var anArray = [
    ["A1", "B1", "C1"],
    ["A2", "B2", "C2"],
    ["A3", "B3", "C3"],
    ["A4", "B4", "C4"],
    ["A5", "B5", "C5"],
    ["A1", "B1", "C1"],
    ["A2", "B2", "C2"],
    ["A3", "B3", "C3"],
    ["A4", "B4", "C4"],
    ["A5", "B5", "C5"]
];


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

var i, j;


for (i = 1; i < anArray.length; i++) {
    // create a new row
    var newRow = table.insertRow(tables.length);


    for (j = 0; j < anArray[i].length; j++) {
        // create a new cell
        cell = newRow.insertCell(j);

        // add value to the cell
        cell.innerHTML = anArray[i][j];

        tables.rows[i].cells[j].onclick = function() {

            //    var result = tables.rows[i].cells.item(j).innerHTML; 
            rIndex = this.parentElement.rowIndex + 1;
            cIndex = this.cellIndex;
            var result = tables.rows[rIndex].cells[cIndex].item().innerHTML; // this line of code that I was confused.
            console.log("Row : " + rIndex + " , Cell : " + cIndex);
            console.log(result);
        }
    }
}

我很困惑如何返回多維數組的值? 每次單擊表格單元格時,我都想控制台記錄每個單元格的值,每次單擊時? 什么是正確的稱呼? 有什么建議么?

我對你的問題也有點不確定。 我能給你的最簡單的答案或建議可能是在每個單元格上都有一個 function 調用,有幾種方法可以解決它。 看看這里:

使用 HTML 按鈕調用 JavaScript function

您可以用tr標簽交換input標簽。

獲取結果的代碼中存在問題,只需從該行中刪除.item()

var result = tables.rows[rIndex].cells[cIndex].innerHTML;

然后它將console.log()你的結果:

 var anArray = [ ["A1", "B1", "C1"], ["A2", "B2", "C2"], ["A3", "B3", "C3"], ["A4", "B4", "C4"], ["A5", "B5", "C5"], ["A1", "B1", "C1"], ["A2", "B2", "C2"], ["A3", "B3", "C3"], ["A4", "B4", "C4"], ["A5", "B5", "C5"], ]; var tables = document.getElementById("table"); var i, j; for (i = 1; i < anArray.length; i++) { // create a new row var newRow = table.insertRow(tables.length); for (j = 0; j < anArray[i].length; j++) { // create a new cell cell = newRow.insertCell(j); // add value to the cell cell.innerHTML = anArray[i][j]; tables.rows[i].cells[j].onclick = function () { // var result = tables.rows[i].cells.item(j).innerHTML; rIndex = this.parentElement.rowIndex + 1; cIndex = this.cellIndex; var result = tables.rows[rIndex].cells[cIndex].innerHTML; // this line of code that I was confused. console.log("Row: " + rIndex + ", Cell: " + cIndex); console.log(result); }; } }
 <table id="table"> <!-- The Row Number 0 --> <th>First Name</th> <th>Last Name</th> <th>Age</th> <!-- End Row Number 0 --> </table>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM