mardi 29 septembre 2015

HTML/Javascript How to put id's into an array and randomly choose from it?

So this is what I have,

<body>
<h1 style= "text-align:center">Welcome to John's Tic Tac Toe Game</h1>
<script type="text/javascript">
</script>
<div>
<table align="center" border="1" style="width:50%; height:50%; text-    align:center">
<tr>
<td id = "topLeft"></td>
<script>
    document.getElementById('topLeft').onclick = function() {
        document.getElementById('topLeft').style.cssText = "background-color:red";
    }
</script>
<td id = "topMiddle"></td>
<script>
    document.getElementById('topMiddle').onclick = function() {
        document.getElementById('topMiddle').style.cssText = "background-color:red";
    }
</script>
<td id = "topRight"></td>
<script>
    document.getElementById('topRight').onclick = function() {
        document.getElementById('topRight').style.cssText = "background-color:red";
    }
</script>
</tr>
<tr>
<td id = "middleLeft"></td>
<script>
    document.getElementById('middleLeft').onclick = function() {
        document.getElementById('middleLeft').style.cssText = "background-color:red";
    }
</script>
<td id = "middleMiddle"></td>
<script>
    document.getElementById('middleMiddle').onclick = function() {
        document.getElementById('middleMiddle').style.cssText = "background-color:red";
    }
</script>
<td id = "middleRight"></td>
<script>
    document.getElementById('middleRight').onclick = function() {
        document.getElementById('middleRight').style.cssText = "background-color:red";
    }
</script>
</tr>
<tr>
<td id = "bottomLeft"></td>
<script>
    document.getElementById('bottomLeft').onclick = function() {
        document.getElementById('bottomLeft').style.cssText = "background-color:red";
    }
</script>
<td id = "bottomMiddle"></td>
<script>
    document.getElementById('bottomMiddle').onclick = function() {
        document.getElementById('bottomMiddle').style.cssText = "background-color:red";
    }
</script>
<td id = "bottomRight"></td>
<script>
    document.getElementById('bottomRight').onclick = function() {
        document.getElementById('bottomRight').style.cssText = "background-color:red";
    }
</script>
</tr>

</table>
</div>


</body>

What ends up showing up from this is a table and when I click on a box, it turns red. I am trying to get the computer to make a random decision as to where to make a square blue. I thought of making an array of all the different id's i have for each table data and making it choose randomly which one to turn blue, but I couldn't insert the id's into an array because it just reads it as a string. I was wondering if any of you guys could help me solve this or suggest a better way of choosing a random square.

Thanks!




Aucun commentaire:

Enregistrer un commentaire