每个循环仅显示最后一个实例

时间:2015-03-30 18:51:14

标签: jquery each

嗨,我的每个循环都有问题。当我运行外部每个循环时,记录的数据会多次显示最后一个实例,而不是显示每个实例。

似乎问题出在.push上,因为the_data的日志正常工作

//Set variables
var links = [];
var the_data = [];

//Loop through each instance of .section
$.each($('.section'), function(index, item) {

    //find all instances of .item within .section
    var data = $(this).find('.Item');

    //loop through each instance of .item and find all data attributes and add them to an array
    $(data).each(function() {
        var name = $(this).attr('data-name'); 
        the_data[name] = $(this).val();
    });

    //log the_data to check
    console.log(the_data);

    //push the_data array into links
    links.push(the_data);
});

//log links to check
console.log(links);

这是控制台输出:

[articleTitle: "title", articleOutlet: "outlet", articleLink: "link", articleExcerpt: "Excerpt"]
[articleTitle: "title 2", articleOutlet: "outlet 2", articleLink: "link 2", articleExcerpt: "Excerpt 2"]
[Array[0], Array[0]]0: 
Array[0]articleExcerpt: "Excerpt 2"articleLink: "link 2"articleOutlet: "outlet 2"articleTitle: "title 2"length: 0__proto__: Array[0]1: 
Array[0]articleExcerpt: "Excerpt 2"articleLink: "link 2"articleOutlet: "outlet 2"articleTitle: "title 2"length: 0__proto__: Array[0]length: 2__proto__: Array[0]

3 个答案:

答案 0 :(得分:1)

the_data是一个数组,在您的示例中初始化一次。您的代码每次都将同一个数组推送到links ,因此它当然会多次显示相同的数据。

您需要将the_data重置为外部each循环内的新数组

$.each($('.section'), function(index, item) {
    the_data = [];

或者只是在外部循环中声明它:

$.each($('.section'), function(index, item) {
    var the_data = [];

由于您似乎使用the_date作为名称/值字典,而不是数组,因此您可以将其声明为对象:

$.each($('.section'), function(index, item) {
    var the_data = {};

答案 1 :(得分:1)

每次执行links.push(the_data)时,您都会将同一个数组推送到links数组。它没有复制它。您应该在外部the_data循环内初始化$.each()。此外,看起来the_data应该是一个对象,而不是一个数组,因为您将name: value对存储在其中。数组用于数字索引数据。

//Loop through each instance of .section
$.each($('.section'), function(index, item) {
    var the_data = {};
    ...
}

答案 2 :(得分:0)

看起来你正在用第二个条目覆盖第一个条目。