【问题标题】:jquery json parsingjquery json解析
【发布时间】:2011-01-24 02:03:04
【问题描述】:

我有一张有 4 层的地图,每层都有不同商店的标记。我需要做的就是这个。

  • 用户从选择中选择商店
  • 脚本获取商店名称,然后从 json 中找到该商店的正确数据。

我对脚本的外观有一个粗略的了解,但不知道如何正确编写。

$('#shopselect').change(function() {
    $.ajax({
    type: "GET",
    url: "data.txt",
    dataType: "json",
    success: function(data) {

    var selected = $('#shopselect option:selected').text()

    if ($(".layer1:visible").length) {
        $("#viewport").mapbox("center", { 
            x: shops." + selected + ".l1x, 
            y: shops." + selected + ".l1y 
        });
    } else if ($(".layer2:visible").length) {
        $("#viewport").mapbox("center", { 
            x: shops." + selected + ".l2x, 
            y: shops." + selected + ".l1y 
        });
    } else if ($(".layer3:visible").length) {
        $("#viewport").mapbox("center", { 
            x: shops." + selected + ".l3x, 
            y: shops." + selected + ".l1y 
        });
    } else if ($(".layer4:visible").length) {
        $("#viewport").mapbox("center", { 
            x: shops." + selected + ".l4x, 
            y: shops." + selected + ".l1y 
        });
    }
}
});

json 看起来是这样的。

{
shops:{
    primark:{
        l1x:310,
        l1y:132,
        l2x:388,
        l2y:264,            
        l3x:530,
        l3y:355,
        l4x:670,
        l4y:450
    },
    boots:{
        l1x:310,
        l1y:132,
        l2x:388,
        l2y:264,            
        l3x:530,
        l3y:355,
        l4x:670,
        l4y:450
    }       
}

}

有没有人可以为我指明正确的方向。

【问题讨论】:

    标签: jquery json


    【解决方案1】:

    而不是使用这个:

    x: shops." + selected + ".l1x, 
    y: shops." + selected + ".l1y 
    

    这样的事情怎么样:

    x: data.shops[selected].l1x, 
    y: data.shops[selected].l1y 
    

    【讨论】:

    • JSON 在函数参数数据中,所以你需要使用 x: data.shops[selected].l1x, y: data.shops[selected].l1y
    • @David:呃,我专注于语法,没有检查变量:-(我已经编辑了我的答案;感谢您的评论!
    【解决方案2】:

    假设你得到的价值:

    var selected = $('#shopselect option:selected').text()
    

    (顺便说一下,你在这里忘了分号)要么是“primark”,要么是“boots”, 您应该可以通过这种方式访问​​数据:

    var coords = data.shops[selected];
    if ($(".layer1:visible").length) {
        $("#viewport").mapbox("center", { 
            x: coords.l1x, 
            y: coords.l1y 
        });
    

    等等

    【讨论】:

      【解决方案3】:

      你可以这样做来获得商店:

      var shops = data.shops;
      

      获取店铺属性的正确方法是:

      shops[selected].l4x
      

      换句话说,将商店视为关联数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-18
        • 2013-01-21
        • 2014-08-28
        • 2012-05-14
        • 2015-05-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多