问题描述
我想用数组中的数据填充一个下拉列表。如果我使用angularJS,下面的代码是我会做的事情。我想知道是否有办法在javascript中执行此操作,或者以某种方式允许ng-options在这里工作。
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,center: myLatlng
};
var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
var city = ["NewYork","Chicago","Florida"];
var contentString =
`<div class="dropdown">
<select>
<option ng-options="item for item in ${city}">{{item}}</option>
</select>
</div>`;
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: myLatlng,map: map,title: 'Uluru (Ayers Rock)',// zIndex: Math.round(myLatlng.lat() * -100000) << 5
});
google.maps.event.addListener(marker,'click',function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
演示:https://jsfiddle.net/spdmu6we/5/
解决方法
根据您的评论,您希望不使用HTML''。
因此,您有两个选择:1.使用字符串解析来构建HTML字符串,然后将其作为内容传递。2.将您拥有的字符串解析为DOM节点并使用我提供的代码。
这将GMap内容替换为通用代码。您仍然可以使用与DOM相关的代码。
这是一个解决方案:
var city = ["NewYork","Chicago","Florida"];
const pre = '<div class="dropdown"><select>';
const post = '</select></div>';
let options = '';
city.forEach(city => {
let o = `<option value=${city}>${city}</option>`;
options += o;
});
content = pre + options + post;
var infowindow = document.createElement('div');
infowindow.innerHTML = content;
infowindow.style.display = 'none'
var marker = document.createElement('button');
marker.innerText = "Click me";
marker.addEventListener('click',() => {
document.body.appendChild(infowindow);
infowindow.style.display='block';
});
document.body.appendChild(marker);
<div id="map-canvas"></div>
,
在javascript中创建许多元素的两种典型方式是:
-
将一长串元素组合在一起,例如
"<option>Banana</option><option>Apple</option>"
,然后在父select
上使用.innerHTML -
使用JavaScript像
document.createElement("OPTION")
和.appendChild
一样独立地创建每个节点。
每种都有性能上的影响。但是本机javascript不会做这种模板。