简体   繁体   English

CSS:在for循环中使用nth-child

[英]CSS: Using nth-child in a for loop

I am trying to creat three arrays, and fill them with specific information gathered from each child element of tr. 我正在尝试创建三个数组,并用从tr的每个子元素收集的特定信息填充它们。

I keep on getting a syntax error, however the code below works fine when I replace the child element with a number (it just fills the entire array with the same string). 我不断收到语法错误,但是当我用数字替换子元素时,下面的代码可以正常工作(它只是用相同的字符串填充整个数组)。

I've been stuck on this for a while, so any syntax help would be much appreciated! 我已经坚持了一段时间,所以任何语法帮助将不胜感激! Am I approaching this the right way? 我是否采用正确的方法?



var str = new Array ();

for (i =1; i<=5; i++){

str[i] = $("tr:nth-child(i+2) > td.short-desc > a > div > div.col-lg-5.col-         sm-6.hidden-xs > div.pull-left > div > div:nth-child(2) > img ").attr('src')
 }

var pos = new Array ();

for (i=1; i<=5; i++){
pos[i] = str[i+2].search("traveler/");
}

var rating = new Array ();

for (i=1; i<=5; i++){
rating[i] = str[i+2].substring(pos[i+2]+ 9, pos[i+2] +12);
}

jQuery selectors have no access to the surrounding context, so they can't see the variable i . jQuery选择器无法访问周围的上下文,因此它们看不到变量i You have two options: 您有两种选择:

  1. Calculate the value in the loop and then pass the result to jQuery: $("tr:nth-child(" + (i+2) + ") > ..." 计算循环中的值,然后将结果传递给jQuery: $("tr:nth-child(" + (i+2) + ") > ..."

  2. Get a list of <tr> elements, iterate over them and then use a selector on each element. 获取<tr>元素的列表,对其进行迭代,然后在每个元素上使用选择器。

The second solution look like so: 第二种解决方案如下所示:

var rows = $('<tr>'); // get all rows as array

for( i=1; i<=5; i++) {
   // search a child of a certain row
   $("td.short-desc > a > div > ...", rows[i+2]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM