2017-04-09 82 views
0

下面是我执行生成宾果卡的HTML代码:JavaScript的宾果游戏 - 让细胞可点击

... 
        <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(); 
} 

回答

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

+0

谢谢:)我可以看到它,当我在JSfiddle中试用它时,但是当我将代码$(文档)...放入我的.js文件并运行程序时,我仍然无法单击单元格。将JQuery放在.js文件中,你需要做什么? –

+1

@RosaryLightningX不客气,我会尽快更新我的答案,但我很想知道downvote背后的推理。 –

+0

我很好奇,我没有downvote这个答案。 –

1

我只想添加一个按钮元素的TD元素里面,然后把它处理这样的。

+0

你能否解释一下?所以我尝试了类似于“  ”并且它似乎没有工作。 –

+0

对不起。是的,我试图说要在td中包装一个按钮。所以不是type =,而是另一个元素。但是,其他答案看起来不错,如果它的工作:) –

+0

啊......好吧,我有点看到你的意思。然而,不确定确切的实施。有没有一个页面可以给我更多的细节? –