如何使用复选框隐藏函数内的元素?

时间:2018-10-26 22:28:40

标签: javascript

我正试图实时隐藏地图上的所有图钉。

我已经可以从复选框(false)中获得truevar getcheck,但是它不能实时运行。当我尝试单击复选框时,setVisible(false)setVisible(true)将不起作用。

此外,我不想在输入中添加onclick='initMap()',因为这样我的地图将再次加载。

HTML

<input type='checkbox' value='1' id='show_location' checked>
<div id="map"></div>

JS

function initMap() {

var map;
var markers = [];
var locations = ['<div id="content"> <div id="siteNotice"></div> <h2 id="firstHeading" class="firstHeading">dfgdfgdf</h2> <div id="bodyContent"> <p>gdfgdf</p> <p>Location: Detroit, MI, USA</p> <p>Has been there at October 25, 2018, 6:50 pm.</p> </div> </div>', 42.331429, -83.045753, '5'],];

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 2,
  center: new google.maps.LatLng(0, 0)
});

var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

var markers = locations.map(function(location, i) {
  return new google.maps.Marker({
    position: location,
    label: labels[i % labels.length]
  });
});

var pinBase = '<?=$static_url?>/img/user/pin-';
var pushpinBase = '<?=$static_url?>/img/user/pushpin-';

var num_markers = locations.length;
for (var i = 0; i < num_markers; i++) {
  markers[i] = new google.maps.Marker({
    position: {lat:locations[i][1], lng:locations[i][2]},
    map: map,
    html: locations[i][0],
    id: i,
    icon: pinBase + locations[i][3] + '.png'
  });

  google.maps.event.addListener(markers[i], 'click', function(){
    var infowindow = new google.maps.InfoWindow({
      id: this.id,
      content: this.html,
      position: this.getPosition(),
      maxWidth: 340
    });
    google.maps.event.addListenerOnce(infowindow, 'closeclick', function(){
      markers[this.id].setVisible(true);
    });
    this.setVisible(false);
    infowindow.open(map);
  });

  var getcheck = document.getElementById('show_location').checked;

  // here
  alert(getcheck);

  if (getcheck == false) {
    markers[i].setVisible(false);
  } else {
    markers[i].setVisible(true);
  }
}

}

1 个答案:

答案 0 :(得分:2)

使用for (var i = 0; i < num_markers; i++),您可以获取所有标记并仅执行一次操作(如果您想使用.addEventListener()则很好)。

在这种情况下,您应该将点击/更改事件监听器直接置于复选框,然后隐藏/显示所有标记。替换代码

var getcheck = document.getElementById('show_location').checked;

  // here
  alert(getcheck);

  if (getcheck == false) {
    markers[i].setVisible(false);
  } else {
    markers[i].setVisible(true);
  }
}

使用以下代码

var checkbox = document.getElementById('check');
toggleMarkers(checkbox);

checkbox.addEventListener('change', (e) => {

  toggleMarkers(checkbox);

}).bind(checkbox);


let toggleMarkers = (checkbox) => {

  let isChecked = checkbox.checked;
  markers.map((elem) => {
      elem.setVisible(isChecked);
  });
}