2012-07-14 133 views
0

我得到li元素的id,並且想要使用該名稱來訪問對象的該部分。我試圖添加包含我想要的部分的名稱的var selectionId,例如cars,但出現錯誤。有沒有辦法?將字符串傳遞到對象javascript

謝謝。

$(document).ready(function() { 

    $(".markerSelection").click(function() { 
     var selectionId = $(this).attr("id"); 
     drop(selectionId); 
    }); 
}); 


var markers = { 
    shopping : [ 
    new google.maps.LatLng(52.26183, -7.11339), 
    new google.maps.LatLng(52.26134, -7.11226), 
    new google.maps.LatLng(52.26067, -7.11181), 
    new google.maps.LatLng(52.26003, -7.11033)], 
    cars : [ 
    new google.maps.LatLng(52.26183, -7.11339), 
    new google.maps.LatLng(52.26134, -7.11226), 
    new google.maps.LatLng(52.26067, -7.11181), 
    new google.maps.LatLng(52.26003, -7.11033)] 
}; 

var iterator = 0; 

function drop(selectionId) { 
    clearOverlays(); 
    for (var i = 0; i < markers.selectionId.length; i++) { 
     setTimeout(function() { 
      addMarker(); 
     }, i * 200); 
    } 
} 

回答

4

如果您正在試圖通過一個可變密鑰來訪問一個對象的屬性,你需要使用數組表示法:

... markers[selectionId].length ... 

markers.selectionId失敗,因爲它相當於markers["selectionId"]

+0

什麼downvote? -innocent halo- * [可能會或可能沒有刪除downvote由於曲解答案] * – 2012-07-14 22:18:28

+0

謝謝:D刪除我的評論 – Hamish 2012-07-14 22:19:01

+0

不客氣。實際上,+1是正確的。 – 2012-07-14 22:19:20

相關問題