2010-02-06 35 views
1

我想在jQuery中得到一个随机单元格,1-16之间,我有随机数字代码在Javascript中。现在我想要做的就是使用该随机数,并使表的指针指向该随机数?这将如何完成。这是我的随机数字代码。从jQuery的表中获取随机单元格

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

这应该给我进入某种方式得到一个随机单元格的引用表

+3

请花时间来提供更多的信息,如表的代码,你想要完成的任务的解释。我不知道“制作表格的指针”是什么意思。 – user113716 2010-02-06 00:58:29

+1

为了防止其他人提到这一点,您使用这个jQuery选择器'$('#board')'将目标设置为“board”。你上面的代码缺少哈希#。 – Mottie 2010-02-06 01:47:11

回答

2

甲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

我认为不是使用'16',而是用'​​'的数字代替'var randomNum = Math.floor(Math.random()* $('td').length) '这样你可以改变桌子的大小,而不必更改代码 – Mottie 2010-02-06 01:35:03

+0

@fudgey - 好主意。使其变得灵活。我会添加该选项。 – user113716 2010-02-06 01:38:08

+0

它确实给出了随机结果,但我想要的是一种获取随机小区的方法,并且也获得了随机小区的位置。假设我随机得到数字10,那么我也想到10号单元格。顺便说一句我正在与一张4x4桌子一起工作。 – Zerobu 2010-02-06 03:56:38

1

var randomNum = Math.floor(Math.random()* 16);
变种randomtd = $( 'TD')当量(randomNum - 1)

相关问题