我正在尝试创建一个代码片段,从数据库中获取谷歌地图对象,如位置,标记文本,并将其添加到html数据属性,以便我可以在javascript中轻松使用它们
我无法让js将json理解为json,而是将其视为字符串
jQuery('.map_canvazz').each(function(i,elem) {
latPos = jQuery(this).attr("data-lat");
longPos = jQuery(this).attr("data-long");
infoDisplay = jQuery(this).attr("data-info");
var objAddresses= jQuery(this).attr("data-params");
if(typeof objAddresses != 'undefined'){
console.log(typeof(objAddresses));
console.log(objAddresses);
//array of object is treated as string
// unable to convert array of objects as json
// todo :- loop through the object of array
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='map_canvazz' id='maper1' data-params='[{"lat":"-36.758435","long":"144.273174","mapTxt":"<div class=\"mapArea\"><div class=\"lineOneMap\">Beyond Medical Education Victorian Office<\/div><div class=\"lineTwoMap\">37 Rowan Street<br>Bendigo VIC 3550, Australia<br>+61 35441 9300<\/div><\/div>"},{"lat":"1111","long":"222","mapTxt":"test"}]'></div> </div>
答案 0 :(得分:2)
属性值只能是字符串。如果要将JSON字符串转换为JavaScript对象,则应通过JSON.parse()
运行它。
答案 1 :(得分:1)
使用.data()
jq方法。它会将其解析为数组:
jQuery('.map_canvazz').each(function(i, elem) {
var objAddresses = jQuery(this).data("params");
for (var i = 0; i < objAddresses.length; i++) {
var obj = objAddresses[i];
console.log(obj.lat, obj.long, obj.mapTxt);
}
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='map_canvazz' id='maper1' data-params='[{"lat":"-36.758435","long":"144.273174","mapTxt":"<div class=\"mapArea\"><div class=\"lineOneMap\">Beyond Medical Education Victorian Office<\/div><div class=\"lineTwoMap\">37 Rowan Street<br>Bendigo VIC 3550, Australia<br>+61 35441 9300<\/div><\/div>"},{"lat":"1111","long":"222","mapTxt":"test"}]'></div>
</div>
&#13;