Javascript:ForEach循环通过此方法访问json标记的正确方法

时间:2015-06-05 17:57:24

标签: javascript php json foreach

为了只获取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")
        )
    ),

执行此操作的正确语法是什么?感谢您的帮助

1 个答案:

答案 0 :(得分:1)

试试这个:

http://jsfiddle.net/kzzphmrp/

您的代码看起来有些问题:

  • 您似乎使用字符串作为ID,但与javascript循环中的数字进行比较
  • 你有一个多余的循环,如果你正在做foreach,你在回调中得到数组单个元素,所以你不需要再次遍历整个数组(就像你在这里做的那样: for (var i = 0; i < element.length; i++) { ... })只需移除此循环并遍历元素“展览”属性:for (var j = 0; j < element.exhibits.length; j++)
  • 纠正了HTML输出的一些问题,我想你忘了“alt”那里

我想要实现这个目标吗?