gpt4 book ai didi

javascript - jQuery根据整数创建一定数量的元素

转载 作者:行者123 更新时间:2023-11-30 14:06:34 24 4
gpt4 key购买 nike

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

例如:

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

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

最佳答案

您可以使用带有 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

关于javascript - jQuery根据整数创建一定数量的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55269291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com