1

我正在使用 WordPress,在 JS 中我有多个实例,我正在将数据从 PHP 传递到 JS

<script type='text/javascript'>
/* <![CDATA[ */
var googlemaps_165 = {"markers":[[....]],"zoom":""};
var googlemaps_169 = {"markers":[[....]],"zoom":""};
/* ]]> */
</script>

在 HTML 我有这个

<div class="wpmaps wpmaps--165" data-id="googlemaps_165"></div>
<div class="wpmaps wpmaps--169" data-id="googlemaps_169"></div>

在 JS 中,我可以像这样手动处理数据

var markers = googlemaps_165.markers

但是我怎样才能动态地做到这一点?

var wpmaps = document.querySelectorAll('.wpmaps');

for (var i = 0; i < wpmaps.length; ++i) {

    // this gives me "googlemaps_165" which is correct
    var dataName = wpmaps[i].getAttribute('data-id');

    // But I can't do this since dataName in this case is only a name, I can't access it this way
    var markers = dataName.markers;

}
4

1 回答 1

3

全局变量是window对象的属性,您可以使用方括号 ( []) 表示法动态访问它们:

var wpmaps = document.querySelectorAll('.wpmaps');

for (var i = 0; i < wpmaps.length; ++i) {

  // this gives me "googlemaps_165" which is correct
  var dataName = wpmaps[i].getAttribute('data-id');

  // But I can't do this since dataName in this case is only a name, I can't access it this way
  var markers = window[dataName].markers;

  console.log(markers);
}
<script type='text/javascript'>
  /* <![CDATA[ */
  var googlemaps_165 = {
    "markers": [
      [1]
    ],
    "zoom": ""
  };
  var googlemaps_169 = {
    "markers": [
      [2]
    ],
    "zoom": ""
  };
  /* ]]> */
</script>
In HTML I have this

<div class="wpmaps wpmaps--165" data-id="googlemaps_165"></div>
<div class="wpmaps wpmaps--169" data-id="googlemaps_169"></div>

您还可以使用NodeList.forEach()迭代节点而不是 for 循环,并data-id通过元素数据集访问:

document.querySelectorAll('.wpmaps')
  .forEach(function(wpmap) {
    var dataName = wpmap.dataset.id;
    
    var markers = window[dataName].markers;
    
    console.log(markers);
  });
<script type='text/javascript'>
  /* <![CDATA[ */
  var googlemaps_165 = {
    "markers": [
      [1]
    ],
    "zoom": ""
  };
  var googlemaps_169 = {
    "markers": [
      [2]
    ],
    "zoom": ""
  };
  /* ]]> */
</script>
In HTML I have this

<div class="wpmaps wpmaps--165" data-id="googlemaps_165"></div>
<div class="wpmaps wpmaps--169" data-id="googlemaps_169"></div>

于 2020-01-04T20:30:35.697 回答