【问题标题】:I am having troubles with looping in javascript/jquery我在 javascript/jquery 中循环时遇到问题
【发布时间】:2015-07-01 14:45:39
【问题描述】:

我有以下代码。每当我更改数组中的值时 - data[0]data[1] 值都会更改。我在data 数组中存储了大约 4 个项目。

$(document).ready(function() {
  $.ajax({
    cache: false,
    url: "http://<mywebsite>/user/id/1",
    type: 'GET',
    crossDomain: true,
    dataType: 'json',
    success: function() {
        alert("Success");
    },
    error: function() {
        alert('Failed!');
    },
  }).then(function(data) {
    var result = data [1];
    console.log(result);
    $('.ch-name').append(result.ch_name);
    $('.ch-logo').append(result.ch_logo);
    $('.ch-desc').append(result.ch_desc);
    $('.ch-genre').append(result.ch_genre);
  });

});

我想显示数组中的所有数据。我怎么做?我试过这样做,但没有奏效。我也尝试过其他方法,但仍然如此。

  $(document).ready(function() {
      $.ajax({
        cache: false,
        url: "http://<mywebsite>/user/id/1",
        type: 'GET',
        crossDomain: true,
        dataType: 'json',
        success: function() {
            alert("Success");
        },
        error: function() {
            alert('Failed!');
        },
    }).then(function(data) {
        var result = data [1];
        console.log(result);

    for (i = 0; i < result.length; i++) {
        $('.ch-name').append(result[i].ch_name);
        $('.ch-logo').append(result[i].ch_logo);
        $('.ch-desc').append(result[i].ch_desc);
        $('.ch-genre').append(result[i].ch_genre);
    }    
  });
});

【问题讨论】:

  • 你收到的data是什么格式的?
  • “没用”是什么意思?
  • 你的console.log(result);是什么样的?
  • 这取决于结果数组的内容,您可以发布console.log输出吗?
  • @Huey 这是一个数组。数据类型为json。

标签: javascript jquery arrays loops


【解决方案1】:

描述有点不清楚,但我想我明白你在做什么。

应该通过将 for 循环更改为循环数据而不是结果来完成

for (i = 0; i < data.length; i++) {
    $('.ch-name').append(data[i].ch_name);
    $('.ch-logo').append(data[i].ch_logo);
    $('.ch-desc').append(data[i].ch_desc);
    $('.ch-genre').append(data[i].ch_genre);
} 

如果这不是您想要做的,请发布数据结构是什么样的,以及您希望如何显示它

【讨论】:

  • 嗨,感谢您的宝贵时间。您的脚本帮助从数组中获取所有内容并显示它。但是有一点问题,不确定是 for 循环还是 css 错误。这就是我设置数组中第一个数据的样式(查看通道区域)link。所以我在想如果我应该抓取其余的数据,它们将统一出现在它的下方。但不,一切都是混合的;这就是它的样子 - link
  • 数据的 URL 是 link 。谢谢。
  • 你正在做一个循环,每次都将数据附加到同一个元素;所以您发布的第二个链接是正常行为(“.ch-name”元素将包含所有名称的串联,依此类推);我认为您应该为 4 ch 元素创建一个容器 div,并在每个周期中克隆它
  • @CerealKiller 谢谢。我应用了你刚才认为我的东西。对于只有 4 个元素,这似乎不是问题。如果它有大约 100 个元素,那将是一件痛苦的事情。谢谢
  • 有很多方法可以解决这个问题,我做了一个小例子作为起点:jsbin.com/gudacikusu/1/edit?css,js,output
猜你喜欢
  • 2017-05-19
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多