for (i = 1; i < 24; i++){{
if(dices[i].value == 0) {
$('td div:nth-child(i)').addClass("zero-desktop")
} else if (dices[i].value == 1) {
$('td div:nth-child(i)').addClass("one-desktop")
} else if (dices[i].value == 2){
$('td div:nth-child(i)').addClass("two-desktop")
} else if (dices[i].value == 3) {
$('td div:nth-child(i)').addClass("three-desktop")
} else if (dices[i].value == 4) {
$('td div:nth-child(i)').addClass("four-desktop")
} else {
alert ("NOT WORKING")
}
}};
dices[i]
是一个显示23个随机数的数组,有23个div。
每次 dice[i].value
等于 (0~4) 之一时,class 将被添加到 div 并且当它成功添加一个 class 到 div 时,[i]
将递增,直到到达结束数字。
出于某种原因,出现了未捕获的错误:语法错误,无法识别的表达式::nth-child 错误。
最佳答案
这里的问题是您实际上是在选择器中插入字符 'i'
而不是使用变量 i
。您应该使用字符串连接,如下所示:
for (i = 1; i < 24; i++) {
if (dices[i].value == 0) {
$('td div:nth-child(' + i + ')').addClass("zero-desktop")
} else if (dices[i].value == 1) {
$('td div:nth-child(' + i + ')').addClass("one-desktop")
} else if (dices[i].value == 2){
$('td div:nth-child(' + i + ')').addClass("two-desktop")
} else if (dices[i].value == 3) {
$('td div:nth-child(' + i + ')').addClass("three-desktop")
} else if (dices[i].value == 4) {
$('td div:nth-child(' + i + ')').addClass("four-desktop")
} else {
alert ("NOT WORKING")
}
}
关于javascript - jQuery: For 循环 if else 和 nth-child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43244453/