在 Javascript 中使用类似 ngRepeat 的东西

Using something like ngRepeat in Javascript

我想用数组中的数据填充下拉列表。下面的代码是我在使用 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/

在 javascript 中创建大量元素的两种典型方法是:

  1. 将一长串元素连接在一起,例如 "<option>Banana</option><option>Apple</option>",然后在父 select

    上使用 .innerHTML
  2. 使用javascript像document.createElement("OPTION").appendChild一样独立地创建每个节点。

每个都有性能影响。但是本机 javascript 不做那种模板。

根据您的评论,您更喜欢在没有和 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>