我正在使用以下函数检索一些JSON数据。单击一个元素并使用数据创建表格,使用图像填充单元格并将表格附加到div时调用它。
function LoadImagesByCategory() {
$.getJSON("/Service/GetJson.ashx?data=images", function(data) {
jsObjectData = data.ImageCollection.Images;
//Create a table named imageTable
$("#imagesByCategory").append(imageTable);
}
})
jsObjectData看起来像这样。
{"ImageCollection":
{"Images":
[{ "ImageID":"68",
"CatID":"1",
"Name":"uploadedFile",
"Location":"/Images/Art/Full/68.gif",
"ClipLocation":"/Images/Art/Clips/68.gif",
"FullHeight":"504",
"FullWidth":"451"
},
{ "ImageID":"69",
"CatID":"1",
"Name":"uploadedFile",
"Location":"/Images/Art/Full/69.gif",
"ClipLocation":"/Images/Art/Clips/69.gif",
"FullHeight":"364",
"FullWidth":"500"
},
etc. etc
]
}
}
它包含有关FullHeight和FullWidth等图像的其他信息,我希望能够在单击img时检索这些图像。 例如,如果我将img的id设置为“68ArtImage”,其中68是ImageID,我希望能够将68传递给附加到jsObjectData的函数并检索相应的图像数据。 问题首先是我不知道如何使对象有用。在函数外面,第二个我不知道如何将函数附加到对象。
答案 0 :(得分:4)
再次阅读你的问题后,也许这就是你想要的?
function getImageData(id, json){
for(i in json.ImageCollection.Images){
if( json.ImageCollection.Images[i].ImageID == 69){
return json.ImageCollection.Images[i];
}
}
return false;
}
getImageData
将搜索给定的json对象并返回图像对象(如关联数组),否则为false。
示例:
var json = {"ImageCollection":
{"Images":
[{ "ImageID":"68",
"CatID":"1",
"Name":"uploadedFile",
"Location":"/Images/Art/Full/68.gif",
"ClipLocation":"/Images/Art/Clips/68.gif",
"FullHeight":"504",
"FullWidth":"451"
},
{ "ImageID":"69",
"CatID":"1",
"Name":"uploadedFile",
"Location":"/Images/Art/Full/69.gif",
"ClipLocation":"/Images/Art/Clips/69.gif",
"FullHeight":"364",
"FullWidth":"500"
}
]
}
}
function getImageData(id, json){
for(i in json.ImageCollection.Images){
if( json.ImageCollection.Images[i].ImageID == 69){
return json.ImageCollection.Images[i];
}
}
return false;
}
if(image = getImageData(69, json)){
alert('found the image wooo!');
// now do something with your image object
}
else{
alert('no image with that id found');
}
答案 1 :(得分:0)
这是一些伪代码:
//global
var gImageTable = {};
function LoadImagesByCategory() {
$.getJSON("/Service/GetJson.ashx?data=images", function(data) {
jsObjectData = data.ImageCollection.Images;
// Add the images to the image table
for (var i=0; i < jsObjectData.length; i++) {
var img = jsObjectData[i];
gImageTable[img.ImageId] = img;
}
// Create a table named imageTable. Should add the id into each of the images
// so we can access its data from the click handler
$("#imagesByCategory").append(imageTable);
})
}
// The click handler that knows about image map structure
$("#imagesByCategory").click(function (e) {
// or something smarter to detect that it
// was a click within one of the images
if (e.target.tagName == "IMG") {
var imageData = gImageTable[e.target.id];
console.log(imageData.CatID, imageData.FullHeight);
}
});
这不是我将它投入生产的方式。我讨厌全局变量,所以我会有一个管理该表的对象。然后该对象可以保存对imageTable的引用