开发者

Getting a random cell from a table in jQuery

开发者 https://www.devze.com 2022-12-19 21:02 出处:网络
I am trying to get a random cell in jquery, between 1-16, I have the random number code in Javascript. Now what I want to do is to use that random number, and make the pointer of the table go to that

I am trying to get a random cell in jquery, between 1-16, I have the random number code in Javascript. Now what I want to do is to use that random number, and make the pointer of the table go to that random number? How would this be accomplished. Here is my random number code.

    Math.floor(Math.random() * 16)

    <table id="board" border="3" bgcolor="black"  align="center">
      <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td></td>
        <td></td>
  开发者_JS百科      <td></td>
        <td></td>
      </tr>
      <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
    </table>
    <input type="button" value="Shuffle" onclick="shuffle()"/>
    </body>
</html>

What I actually should have said is reference, I want to get a reference to a random cell by using the random generator code in javascript

$('board tr td')

That should give me some way of entry in the table


A jQuery specific solution is to assign a click event to the button in javascript, and put FiveTools code solution there.

<input type="button" value="Shuffle" id="theButton"/>

javascript:

$('document').ready(function() {

$('#theButton').click(function() {

    // Stores a random number from 0 to 15
    var randomNum = Math.floor(Math.random() * 16);

    // This brings you back up to a range of 1 to 16
    var actualNum = randomNum + 1;

    // Grabs and holds the table cell for that number
    // Example: number 10 would be third row, second column
    var randomtd = $('#board td').eq(randomNum);

    // Calculate and store which row
    // by dividing the generated number by the number of rows, and rounding up
    var whichRow = Math.ceil(actualNum / 4);

    // Calculate and store which column
   // by using modulo to find the remainder of the number divided by the rows
   // If the modulo result is '0', then set it to '4'
    var whichColumn = (actualNum % 4) == 0 ? 4 : (actualNum % 4);

    // Display results in an alert
    alert('theNumber: ' + actualNum + ' row: ' + whichRow + '  column: ' + whichColumn);

   // For fun, and to show that you have the td stored
   // Display the number in the correct td
   // and set the text color to grey, since the table is black
   randomtd.text(actualNum).css({color:'#DDD'});
});

});


var randomNum = Math.floor(Math.random()*16);
var randomtd = $('td').eq(randomNum - 1)

0

精彩评论

暂无评论...
验证码 换一张
取 消