为了仅获取 php 脚本的特定部分,我使用了带有与 id 相关的条件的 foreach,因此它给出了范围内的结果。我现在遇到的问题是如何访问我拥有的信息...我将展示一些示例来帮助说明我的困惑
listCheck.innerHTML = "<img src = " + "./images/" + json[i].exhibits[j].exhibit_image + " Photo Cover' height='200' width='200'>";
访问 json 后,使用标签 Exhibit_image 获取适当的数据。然而,使用 ForEach 对此方法进行调整会导致错误,因为我相信代码不知道我要求什么,我认为这是语法错误
这是我尝试过的代码...
function getNewYork()
{
myExhibitionsView = document.getElementById('exhibitioncontent');
images = document.createElement('ul');
json.forEach( function(element) {
if( element['exhibition_id'] == 1 ){
console.log(element);
for (var i = 0; i < element.length; i++) {
for (var j = 0; j < element[i].exhibits.length; j++) {
list = document.createElement('p');
list.id = 'image';
list.innerHTML = "<img src = " + "./images/" + element[i].exhibits[j].exhibit_image + " Photo Cover' height='200' width='200'>";
console.log(list);
myExhibitionsView.appendChild(images);
images.appendChild(list);
}
}
};
});
}
我正在尝试从这组 json 中提取展览图像网址
array("exhibition_id" => "1", "exhibition_title" => "New York, New York", "exhibition_subject" => "New York", "ticket_price" => "10",
"exhibits" => array(
array("exhibit_id" => "3", "exhibit_title" => "Brooklyn Bridge from City Hall Park", "exhibit_description" => "New York, June 2005", "exhibit_image" => "brooklynbridge.jpg", "photographer" => "MLG"),
array("exhibit_id" => "6", "exhibit_title" => "Central Park, New York", "exhibit_description" => "New York, June 2005", "exhibit_image" => "centralpark.jpg", "photographer" => "MLG"),
array("exhibit_id" => "7", "exhibit_title" => "Chrysler Building at night, New York", "exhibit_description" => "New York, July 2001", "exhibit_image" => "chrysler_building.jpg", "photographer" => "MLG")
),
"locations" => array(
array("location_id" => "1", "location_name" => "Kelvingrove Art Gallery and Museum", "location_postcode" => "G3 8AG"),
array("location_id" => "3", "location_name" => "Walker Art Gallery", "location_postcode" => "L3 8EL"),
array("location_id" => "5", "location_name" => "Tate Modern", "location_postcode" => "SE1 9TG")
)
),
执行此操作的正确语法是什么?感谢您的帮助
最佳答案
试试这个:
您的代码似乎存在一些问题:
- 您似乎使用字符串作为 ID,但与 javascript 循环中的数字进行比较
- 你有一个多余的循环,如果你正在执行 foreach,你会在回调中得到数组单个元素,所以你不需要再次循环整个数组(就像你在这里所做的那样:
for (var i = 0; i < element.length; i++) { ... }
)只需删除此循环并循环遍历元素“exhibits”属性:for (var j = 0; j < element.exhibits.length; j++)
- 更正了 HTML 输出的一些问题,我认为您忘记了“alt”
这就是你想要实现的目标吗?
关于Javascript:ForEach循环通过此方法访问json标签的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30672931/