我正在使用基本的随机播放功能将表中的项连接在一起:
var ratings = ['rating0','rating1','rating2','rating3'];
var shuffle = function(arr) {
for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
return arr;
}
shuffle(ratings);
$("#rating0").html(ratings[0]);
$("#rating1").html(ratings[1]);
$("#rating2").html(ratings[2]);
$("#rating3").html(ratings[3]);
$("#rating4").html(ratings[4]);
然后,评级显示为表格中连续的条目:
<table>
<tr id="ColumnLabels">
<td>Column 1</td>
<td>Column 2</td>
<td>Column 3</td>
<td>Column 4</td>
</tr>
<tr>
<td id = "rating1"></td>
<td id = "rating0"></td>
<td id = "rating2"></td>
<td id = "rating3"></td>
</tr>
</table>
如下面的JSFiddle中所示,我想评估shuffle之后项目的顺序,以确定出现Rating1的列:http://jsfiddle.net/HT89v/38/
我尝试使用.parent().hasClass
来确定每个项目的后洗牌位置(http://jsfiddle.net/HT89v/48/):
<tr>
<span class="column1"><td id = "rating1"></td></span>
<span class="column2"><td id = "rating0"></td></span>
<span class="column3"><td id = "rating2"></td></span>
<span class="column4"><td id = "rating3"></td></span>
</tr>
$(function () {
if ($('#rating1').parent().hasClass('column1')) {
alert('column1');
}
});
我认为<td>
会随机播放,但每个<span>
将保留在同一个地方,这样我就可以识别后洗牌位置;但是,这似乎不起作用。
我非常感谢任何人都可以提供帮助。
答案 0 :(得分:0)
以下是您需要的工作示例。(但我强烈建议您将代码更改为更好的设计)
var ratings = ['rating0','rating1','rating2','rating3'];
var shuffle = function(arr) {
for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
return arr;
}
shuffle(ratings);
//ratings[4] = Math.round(Math.random() * 3) + 7;
$("#rating0").html(ratings[0]);
$("#rating1").html(ratings[1]);
$("#rating2").html(ratings[2]);
$("#rating3").html(ratings[3]);
$(function () {
$("#rowRatings").find('td.ratings').each(function(index) {
if($(this).text()=="rating1")
{
//Result would be the column name that has same index as that of the one with value "rating1"
$("#result").text($('#ColumnLabels td:nth-child('+ (index+1)+')').text());
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
"rating1" is under <span id="result"></span>
<br>
<br>
<br>
<table>
<tr id="ColumnLabels">
<td>Column 1</td>
<td>Column 2</td>
<td>Column 3</td>
<td>Column 4</td>
</tr>
<tr id="rowRatings">
<td id = "rating0" class="ratings"></td>
<td id = "rating1" class="ratings"></td>
<td id = "rating2" class="ratings"></td>
<td id = "rating3" class="ratings"></td>
</tr>
</table>