使用JavaScript的querySelectorAll使用多个收音机

时间:2018-08-13 16:51:02

标签: javascript google-maps

我为每个收音机创建了6个不同的ID,但仍然无法正常工作。我在哪里弄错了?

// this works when I insert #style-selector in one of radios below
// var styleSelector = document.getElementById('style-selector');

var styleSelector = document.querySelectorAll('#do_1, #do_2, #do_3, #do_4, #do_5, #do_6');
map.setOptions({styles: styles[styleSelector.value]});

styleSelector.addEventListener('click', function() {
  map.setOptions({styles: styles[styleSelector.value]});
});


<input type="radio" value="default" checked="checked" name="do_radio" id="do_1">
<input type="radio" value="silver" name="do_radio" id="do_2">
<input type="radio" value="retro" name="do_radio" id="do_3" >
<input type="radio" value="dark" name="do_radio" id="do_4">
<input type="radio" value="night" name="do_radio" id="do_5">
<input type="radio" value="aubergine" name="do_radio" id="do_6">

1 个答案:

答案 0 :(得分:0)

您应该迭代选择并为每个元素添加事件侦听器。

替换

styleSelector.addEventListener('click', function() {
  map.setOptions({styles: styles[styleSelector.value]});
});

对于

styleSelector.forEach(function(elem) {
  elem.addEventListener('click', function() {
    map.setOptions({styles: styles[elem.value]});
  });
});