html 5 属性作为对象的数组被视为字符串

html 5 attribute as array of object being treated as string

我正在尝试创建一个代码片段,从数据库中获取 google 地图对象,例如位置、标记文本,并将其添加到 html 数据属性中,以便我可以在 [=25] 中使用它们=]轻松

我无法让 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>

属性值只能是字符串。如果你想将 JSON 的字符串转换为 JavaScript 对象,那么你应该 运行 通过 JSON.parse().

使用.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);
  }
})
<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>