javascript - Using something like ngRepeat in Javascript
问题描述
I want to populate a drop-down list with data from an array. The code below is something I would do if I was working with angularJS. I want to know if there is a way to do this in javascript or somehow allow ng-options to work here.
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);
});
解决方案
根据您的评论,您更喜欢在没有 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>
推荐阅读
- python - python中的elif语法无效
- java - 套接字(java服务器)和(esp32客户端)的问题
- visual-studio-code - 浏览器中的 VSCode 实时共享视图
- html - 使用 Jsoup 扁平化 HTML 文档
- css - 使用 CSS bootstrap-vue 修改 b-card 标题
- regex - 在所有页面上重写 webconfig URL 的正则表达式
- telecommunication - 如何在 LoRaWAN 中重新创建加入接受下行链路消息?
- css - 为什么 font-variant-numeric: slashed-zero 不适用于我的谷歌字体?
- reactjs - 将 React 组件注入页面和热重载的 Chrome 扩展 - 结合两个样板项目
- alpine.js - x-model 未绑定到 select 上的 [value] 属性