2010-03-05 8 views
0

나는 4 개의 레이어가있는지도가 있으며, 각 레이어에는 다양한 상점의 마커가 있습니다. 내가해야 할 일은 이것이야.jquery json 파싱

  • 사용자 선택
  • 스크립트 잡고 가게 이름에서 상점을 선택하고 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 
    }  
} 

}

올바른 방향으로 날 지점 수있는 사람이 있습니까.

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

그런 일에 대해 무엇 :

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

답변

0

대신이 사용 여기 세미콜론)은 "primark"또는 "boots"이고, 이 데이터에 액세스 할 수 있어야합니다. Y :

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

+0

JSON 함수 파라미터 데이터로되어 있으므로 X 사용해야 할 것이다 : data.shops [설정] .l1x, Y : data.shops [설정] –

+0

.l1y @ 데이비드을 구문에 초점을 맞춘 변수를 확인하지 않았다 :-(나는 내 대답을 편집했습니다; 귀하의 의견을 주셔서 감사합니다! –

+0

고마워요. – Trip

0

가정 당신이 얻을 값 :

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

(그런데 당신이 잊고

0

당신은 상점 얻기 위해이 같은 작업을 수행 할 수 있습니다

var shops = data.shops; 

가게 특성을 얻을 수있는 올바른 방법은 다음과 같습니다

shops[selected].l4x 

을 즉 상점을 연관 배열로 취급합니다. I는 ergh :