2017-03-01 87 views
0

我想一個ID添加到細胞中,所以像0行/列0將有1一個id,0行/列1將有2的ID,等爲表格單元分配一個id?

繼承人,即時通訊我的代碼有工作:

function init() { 

var board = document.getElementById("board"); 
var NUM_ROWS = 6; 
var NUM_COLS = 6; 
for (row = 0; row < NUM_ROWS; row++) { 
    var tr = document.createElement("tr"); 
    for (col = 0; col < NUM_COLS; col++) { 
     var td = document.createElement("td"); 
     var img = document.createElement("img"); 
     img.src = 'images/image0.png'; 
     img.id = 'r' + row + 'c' + col; 
     td.appendChild(img); 
     td.addEventListener("click", function() { 
      var img = this.childNodes[0]; 
      img.src = 'images/image1.png'; 
}); 
    tr.appendChild(td); 
} 
board.appendChild(tr); 

} 
+0

請正確縮進代碼或提供小提琴,否則它幾乎不可讀。 – GMaiolo

回答

0

您可以創建和增加一個id變量分配給每個表格單元格有序的數字標識符:

var board = document.getElementById("board"); 
 
var NUM_ROWS = 6; 
 
var NUM_COLS = 6; 
 
var id = 1; 
 
for (row = 0; row < NUM_ROWS; row++) { 
 
    var tr = document.createElement("tr"); 
 
    for (col = 0; col < NUM_COLS; col++) { 
 
    var td = document.createElement("td"); 
 
    td.id = id++; 
 
    var img = document.createElement("img"); 
 
    img.src = 'images/image0.png'; 
 
    img.id = 'r' + row + 'c' + col; 
 
    td.appendChild(img); 
 
    td.addEventListener("click", function() { 
 
     var img = this.childNodes[0]; 
 
     // showPicture(img); 
 
     console.log(img.id); 
 
    }); 
 
    tr.appendChild(td); 
 
    } 
 
    board.appendChild(tr); 
 

 
}
<table id="board"></table>

相關問題