javascript - 从 jQuery 中的表中获取随机单元格

标签 javascript jquery

我想在 jquery 中获取一个随机单元格,在 1-16 之间,我有 Javascript 中的随机数代码。现在我要做的就是使用那个随机数,让表的指针指向那个随机数?这将如何实现。这是我的随机数代码。

    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>
        <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>

我实际上应该说的是引用,我想通过使用javascript中的随机生成器代码来获取对随机单元格的引用

$('board tr td')

这应该给我一些进入表格的方式

最佳答案

一个 jQuery 特定的解决方案是在 javascript 中为按钮分配一个点击事件,并将 FiveTools 代码解决方案放在那里。

<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'});
});

});

关于javascript - 从 jQuery 中的表中获取随机单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2211483/

相关文章:

javascript - firefox 插件 SDK 不使用新音频播放音频

javascript - MongoDB 将字段和切片投影限制在一起

jquery - 如何更改动态添加元素的CSS?

jquery - click() jquery 函数在新的 div 上不可用

jquery - 可拖动且可调整大小的带有遏制的 div 超出了遏制范围

php - Mysql longtext不会保存某些文本?

javascript - 在 ajax 成功响应中正确附加事件更改

javascript - 如何从 Meteor.js 中方法内部的方法返回错误

javascript - 需要使用JS获取<a>标签的 "id"属性

javascript - Angular Xeditable - 无法使用 onbeforesave 事件获取正确的验证值