【问题标题】:How to random each loop item and on ajax / json data in jquery?如何在 jquery 中随机每个循环项和 ajax / json 数据?
【发布时间】:2023-03-13 07:42:01
【问题描述】:

如何在 jquery 中随机化每个循环项和 ajax / json 数据?

数据.json

{
  "items" : [
    {
      "title" : "new1",
      "content" : "content1"
    },
    {
      "title" : "new2",
      "content" : "content2"
    },
    {
      "title" : "new3",
      "content" : "content3"
    },
    {
      "title" : "new4",
      "content" : "content4"
    }
  ]
}

jquery ajax 获取json

    $.ajax({
        url: 'data.json',
        type: 'get',
        dataType: 'json',
        async: false,
        success: function(data){
              $.each(data.items, function(index,item) {
               var template = '<p>' + item.title + '</p>' + item.content + '<br />'; 

                  $('html').append(template);
                  return index < 1 ; // set 2 item 
              });

        }
     });

如何在 jquery 中随机化每个循环项和 ajax / json 数据?

【问题讨论】:

  • “如何随机化每个循环项” - 你的意思是“我如何随机排序/打乱"items" 数组?”
  • 这里你在代码中留下了一个大括号 }。所以可能这将是错误。以及为什么要返回该值。你知道回报会通过你的循环。
  • 你能发布实际的 json 数据吗?这看起来像是硬编码的。
  • @nnnnnn 是的,我如何随机排序/随机排列限制为 2 个项目的“项目”数组,谢谢帮助!更新json格式

标签: jquery ajax json random


【解决方案1】:

添加'并关闭.each().each()末尾添加});

$.each(data.items, function(index,item) {
    var template = '<p>' + item.title + '</p>' + item.content + '<br />'; });

随机

var random_index = Math.floor(Math.random()*data.length);
var item = data[random_index];

【讨论】:

    猜你喜欢
    • 2012-09-20
    • 2017-05-10
    • 2015-11-06
    • 2015-09-03
    • 2016-07-21
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多