2017-04-09 146 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

啊......好吧,我有點看到你的意思。然而,不確定確切的實施。有沒有一個頁面可以給我更多的細節? –