Jquery将数据数组添加到表行

时间:2016-07-01 02:13:22

标签: javascript jquery

我有一个Jquery代码循环遍历表并选择唯一值,然后使用这些唯一值填充另一个表。我的代码如下:

var items = [], options = [];

//Iterate all td's in first column
$('#PartsTable tr td:nth-child(1)').each(function () {
    //add item to array
    items.push($(this).text());
});

//restrict array to unique fleet numbers
var items = $.unique(items);
});

//iterate unique array and build array of select options
// ERROR HERE - 'ITEMS IS UNDEFINED'
$.each(items, function(i, item) {
    options.push('<tr><td align="left" valign="top">' + item + '</td><td class="delete" align="center" style="background-color: transparent;"><i class="fa fa-times text-red cur-pon"></i></td></tr>');
});

//finally append the items from the array
$('#OrderSummaryTbody').append(options.join());

但是我在上面标记的行上收到错误 - &#39;项目未定义&#39;

当我在Chrome中运行调试器时,var items = $.unique(items);会清楚地返回一个包含2个值的数组。

任何人都可以对此有所了解吗?谢谢!

2 个答案:

答案 0 :(得分:2)

这里有一个错字

var items = $.unique(items);
});

那最后});不应该在这里,或者,这是在一个函数内部,因此items var不是全局的,所以其他代码不能准备它。

如果您可以在此之前显示代码以查看完整的功能,那会更好。

答案 1 :(得分:0)

项目定义为其他块。因此,如果没有该块,您就无法调用它。