我想在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')
这应该会给我一些进入表格的方式
答案 0 :(得分:3)
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'});
});
});
答案 1 :(得分:1)
var randomNum = Math.floor(Math.random()* 16);
var randomtd = $('td')。eq(randomNum - 1)