我正在使用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;
}
全局变量是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
通过elements数据集访问:
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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句