填充动态表获取tr中td的值

时间:2015-01-27 08:16:13

标签: javascript jquery html

var rowCount = $('.destination tr').length;
        for(var i = 1; i > rowCount; i++){
            alert(i);
            var continent = $('.destination').find('tr:nth-child('+i+')').find('td:nth-child(1)').text();
            var country = $('.destination').find('tr:nth-child('+ i +')').find('td:nth-child(2)').text();
            var city = $('.destination').find('tr:nth-child('+ i +')').find('td:nth-child(3)').text();

            //alert(rowCount[i]);

        }

这是来自我的表的代码我希望得到每一行中每个td的值,但它没有返回任何不警告i这里有什么不对。任何想法都是赞赏< / p>

2 个答案:

答案 0 :(得分:0)

问题是你的for循环正在检查"while greater than rowCount"所以它永远不会触发一次!

应该是:

for(var i = 1; <= rowCount; i++)

或更好地使用基于0的索引:

for(var i = 0; < rowCount; i++)

由于您只想迭代行并获得前3个TD,请忘记所有nth-child选择器并以更简单的方式执行此操作:

 var $rows = $('.destination tr');
 $rows.each(function(){
     var $tds = $(this).find('td');
     var continent = $td.eq(0).text();
     var country = $td.eq(1).text();
     var city = $td.eq(2).text();
     // Do something with the values
 });

答案 1 :(得分:0)

实际上,没有jQuery访问表行和单元格会更快,更舒适:

var table = ...;
for (var i = 0, row; row = table.rows[i]; i++) {
   for (var j = 0, col; col = row.cells[j]; j++) {
   }
}

循环条件中的赋值使其在索引用完行/单元格时停止。

请参阅:How do I iterate through table rows and cells in javascript?