【问题标题】:Create a certain number of elements based on integer with jQuery使用 jQuery 基于整数创建一定数量的元素
【发布时间】:2019-03-20 20:02:33
【问题描述】:

我有一个带有 items 类别的 json 文件,其中列出了当前通过数组列出的项目。此项目列表每隔几个小时更新一次。

例如:

{
"items": [
    {
     "name": "Blueberry",
     "img": "website.com/blueberry.png"
    },
    {
     "name": "Raspberry",
     "img": "website.com/raspberry.png"
    }
         ]
}

数组中的每个项目都有一个图像和描述。我想要为每个项目创建一个<img src='(item image url)'> 元素,为项目内列出的图像创建一个<p> 元素,为每个项目列出的描述。

【问题讨论】:

  • 你有没有尝试过获取 Json 数据
  • 我已经通过jquery中的getJSON函数得到了Json数据。我只是在将这些数据转换为 HTML 元素时遇到了问题。
  • 你可以在javascript上使用document.createElement
  • 谢谢。如何将此应用于数组中的每个项目?
  • 看看我发布的答案

标签: javascript jquery json


【解决方案1】:

您可以使用带有 for 循环的 JQuery 来实现这一点,并使用 JQuery 函数 $(...) 动态创建元素(教程 here

最后,你可能会得到这样的结果:

// fetch the items from the url
$.getJSON("your url").then(function(response){

  //cycle through all the items in the array
  for(var i = 0; i < response.items.length; i++){

    // create image
    var image = $('<img>').attr("src", response.items[i].img);
    // make sure to set the attribute using the "attr" function 
    //  to avoid Cross Site Scripting (see the link below)

    // create text element
    var text = $('<p>').text(response.items[i].name);

    // append the items to the container
    $("container element").append(image).append(text);
   }
});

About Cross Site Scripting

【讨论】:

  • @docyoda 没问题!
【解决方案2】:

要在纯 JavaScript 中动态创建元素,您可以使用 document.createElement


var imagesContainer = document.createElement('div')

for(var i = 0; i < array.length; i++){

    var img = document.createElement('img'),
        p = document.createElement('p');

    img.setAttribute("src", array[i].img);

    p.appendChild(document.createTextNode(array[i].name));

    imagesContainer.appendChild(img);
    imagesContainer.appendChild(p);
}

我想这就是你要找的:)

【讨论】:

  • 我在控制台中收到此错误:Uncaught TypeError: Cannot read property 'TextNode' of undefined
  • 对不起,我写错了,是createTextNode 而不是create.TextNode @docyoda
猜你喜欢
  • 2023-04-05
  • 2022-01-03
  • 2020-12-23
  • 1970-01-01
  • 2017-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多