2017-03-07 68 views
0

所以我剛剛開始學習JS,並一直困擾着這個問題。我創建使用JS按鈕的表,轉化爲這HTML:我該如何動態分配自引用onClick到按鈕表?

<table border="1" style="width: 100%; border: none;"> 
<tr> 
    <td class="emptyBorder"> 
     <button class="gridButton" id="button0x0y"></button></td> 
    <td class="emptyBorder"> 
     <button class="gridButton" id="button0x1y"></button></td> 
</tr> 
<tr> 
    <td class="emptyBorder"> 
     <button class="gridButton" id="button1x0y"></button></td> 
    <td class="emptyBorder"> 
     <button class="gridButton" id="button1x1y"></button></td> 
</tr> 
</table> 

我想給他們每個人一個onClick是循環3種不同顏色之間只有自己的顏色。我想,當我在我的JS代碼中創建它們分配這個的onClick他們每個人,但遇到了問題存在,所以我分隔的功能集成到一個新的功能,那就是:

function addOnclickToTable(x, y){ 
    for(var i = 0; i < x; i++) { 
     for (var j = 0; j < y; j++) { 
      var thisId = buttonIDFromXY(i,j); // returns "button{i}x{j}y" 
      var button = document.getElementById(thisId); 
      button.onclick = function() {cycleBackgroundColor(thisID);}; // Changes background color of the element with the given ID 
     } 
    } 
} 

這種分配「的onclick = cycleBackgroundColor ('button1x1y')「給每個按鈕。看起來這個值thisID被保存在JS中,並且在稍後被調用時被引用爲其最後的已知值。有沒有一種方法可以創建它的新實例?有更好的解決方案嗎?

回答

0

你可以這樣做。

var table = document.querySelector('table'); 
 
var buttons = [].slice.call(table.querySelectorAll('.gridButton')); 
 
table.addEventListener('click', function(e) { 
 
    var target = e.target; 
 
    if(buttons.indexOf(target) > -1) { 
 
    var id = target.id; 
 

 
    console.log(id, target); 
 
    // target is your button and id its id 
 
    // do your color circle thing here 
 
    // you could bind the button as `this` to your circle function 
 
    // circleBackgroundColor().bind(target); 
 
    // inside of circleBackgroundColor this.id will give you the button id and this will give you the button. 
 
    } 
 
});
<table border="1" style="width: 100%; border: none;"> 
 
<tr> 
 
    <td class="emptyBorder"> 
 
     <button class="gridButton" id="button0x0y"></button></td> 
 
    <td class="emptyBorder"> 
 
     <button class="gridButton" id="button0x1y"></button></td> 
 
</tr> 
 
<tr> 
 
    <td class="emptyBorder"> 
 
     <button class="gridButton" id="button1x0y"></button></td> 
 
    <td class="emptyBorder"> 
 
     <button class="gridButton" id="button1x1y"></button></td> 
 
</tr> 
 
</table>