jQuery:for if if else和nth-child

时间:2017-04-06 02:04:31

标签: javascript jquery html css

 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)之一时,类将被添加到div中,当它成功地将一个类添加到div时,[i]将递增直到它到达结束编号。

由于某些原因未被捕获错误:语法错误,无法识别的表达式:: nth-child error 出现。

1 个答案:

答案 0 :(得分:3)

这里的问题是,您实际上是在选择器中插入字符'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")
  }
}