JavaScript宾果游戏 - 让细胞可点击

时间:2017-04-09 05:13:27

标签: javascript jquery

以下是我正在实施的用于生成宾果卡的HTML代码:

...
                    <th class="orange">B</th>
                    <th class="orange">I</th>
                    <th class="orange">N</th>
                    <th class="orange">G</th>
                    <th class="orange">O</th>
                </tr>
                <tr>
                    <td id="square0"> &nbsp;</td>
                    <td id="square1"> &nbsp;</td>
                    <td id="square2"> &nbsp;</td>
                    <td id="square3"> &nbsp;</td>
                    <td id="square4"> &nbsp;</td>
                </tr>

                ...

我想知道我怎样才能使单元格(即'td')可点击并触发一个函数来改变.js文件中的颜色?

这是我的.js文件:

var usedNums = new Array(76);

function newCard() {
    //Starting loop through each square card
    for(var i=0; i < 24; i++) {  //<--always this code for loops. change in red
        setSquare(i);
    }
}

function setSquare(thisSquare) {
    var currSquare = "square"+thisSquare;
    var newNum;

    var colPlace =new Array(0,1,2,3,4,0,1,2,3,4,0,1,3,4,0,1,2,3,4,0,1,2,3,4);

    do {
        newNum =(colPlace[thisSquare] * 15) + getNewNum() + 1;
    }
    while (usedNums[newNum]);

    usedNums[newNum] = true;
    document.getElementById(currSquare).innerHTML = newNum;
}

function getNewNum() {
    return Math.floor(Math.random() * 75);

}

function anotherCard() {
    for(var i=1; i<usedNums.length; i++) {
    usedNums[i] = false;
    }

    newCard();
}

2 个答案:

答案 0 :(得分:1)

我只需在td元素中添加一个按钮元素,然后按原样处理它。

答案 1 :(得分:0)

这可能对您有所帮助,HTML:

<table class="coolTable">
  <tr>
    <th class="orange">B</th>
    <th class="orange">I</th>
    <th class="orange">N</th>
    <th class="orange">G</th>
    <th class="orange">O</th>
  </tr>
  <tr>
    <td id="square0"> x</td>
    <td id="square1"> x</td>
    <td id="square2"> x</td>
    <td id="square3"> x</td>
    <td id="square4"> x</td>
  </tr>
</table>

JQuery的:

$(document).on('click', 'td', function() {
    //To change properties of the clicked cell
  $(this).css("background-color", "black");
  $(this).css("font-weight","bold");
  $(this).css('color', 'red');

  //To call a function, or manipulate a function
  newCard();
  //To manipulate a function
  newCard("manipulated a function");
});

function newCard(x) {
    if (x){
    alert(x);
  }
    else{
    alert("called a function");
  }
}

jsfiddle