[英]How to load specific data from JSON file based on ID
我想根據ID從JSON文件加載特定數據。 我在下面顯示基於JSON文件的縮略圖數據列表,然后在單擊事件時加載大圖像。
您可以查看我的代碼以供參考。 我只想知道如何根據單擊事件列表中的ID在JSON文件中找到大圖像。
例如:我想基於“名稱”值從JSON文件中獲取“ largeimg”的值。 在我的HTML中,我想要“ <'li id =“ Red”>”,如果用戶單擊此“ <'li'>”,則基於id =“ Red”的應該與JSON文件中的“ name = Red”匹配,並且從JSON文件的“ largeimg”中獲取值“ /imgs/redlarge.png”
{
"colors": [
{
"name": "Red",
"thumb": "/imgs/redthumb.png",
"largeimg": "/imgs/redlarge.png"
},
{
"name": "Blue",
"thumb": "/imgs/bluethumb.png",
"largeimg": "/imgs/bluelarge.png"
}
]
}
<div class="preview">
<!-- Show data from JSON file based on ID -->
</div>
<div class="list">
<ul class="colors">
</ul>
</div>
$.getJSON('data.json', function (data) {
$.each(data.colors, function (index, value) {
$('.colors').append("<li id='item-"+this.name+"'>"+this.thumb+"</li>");
});
});
$('.list li').click(function(){
console.log($(this).attr('id'));
});
.on()方法將事件處理程序附加到jQuery對象中當前選定的元素集。 [關於方法文件] [1]
對於動態添加的html,您必須使用on方法來附加事件處理程序,如下所示。 為json數據定義全局顏色變量,以搜索數據。
var colors;
$.getJSON('data.json', function (data) {
colors = data.colors;
$.each(data.colors, function (index, value) {
$('.colors').append("<li id='item-"+this.name+"'>"+this.thumb+"</li>");
});
});
$('.list li').click(function(){
var name = $(this).attr('id');
var found;
$.each(colors, function(index, item){
if(item.name == name){
found = item;
}
})
});
if(found){
console.log(found.largeimg);
}
文件大小似乎不是JSON數據文件中提供給您的信息。 因此,我不確定您打算如何按大小排序。 除非,您對使用“ largeimg”作為文件大小感到滿意。 在這種情況下,使用JSON to Java類創建者為您完成此操作可能會有所幫助。
這是一個: https : //timboudreau.com/blog/json/read
您可能需要搜索一個新的,但是通常它允許您解釋JSON數據並訪問特定的數據部分(即圖像大小)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.