Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 每个循环只显示最后一个实例_Jquery_Each - Fatal编程技术网

Jquery 每个循环只显示最后一个实例

Jquery 每个循环只显示最后一个实例,jquery,each,Jquery,Each,嗨,我的每个循环都有问题。当我运行外部each循环时,记录的数据多次显示最后一个实例,而不是显示每个实例 问题似乎出在.push上,因为_数据的日志工作正常 //Set variables var links = []; var the_data = []; //Loop through each instance of .section $.each($('.section'), function(index, item) { //find all instances of .it

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

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

//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]

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

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

您需要将_数据
重置为外部
每个
循环内的新数组

$.each($('.section'), function(index, item) {
    the_data = [];
或者只在外部循环中声明它:

$.each($('.section'), function(index, item) {
    var the_data = [];
由于您似乎将_date
用作名称/值字典,而不是数组,您不妨将其声明为对象:

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

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

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

数组也可以按键进行索引,虽然对象可能是更好的选择。@TrueBlueAussie True,但如果记录数组,它将不会显示命名属性。同意。这是在浪费这个物体的阵列质量。