首页 > 解决方案 > 单击时,我的单选按钮不会更改为选中。我正在尝试使用它来更改显示的内容

问题描述

我正在使用 API 制作一个非常基本的天气应用程序。在我的代码的一部分中,我希望用户单击要显示当前天气的位置的单选按钮。然后我在 JavaScript 中有一个函数来检查单选按钮是否被选中。如果是,它将显示该位置的天气。我遇到的问题是,当用户单击按钮时,这似乎不起作用,并且只有在我手动将 HTML 更改为“checked="true"' 时才起作用。

当用户单击按钮时,有什么想法可以让 html 更改为 'checked="true"'?

function success(pos) {
  if (manchester.checked) {
    var lat = 53.48;
    var long = -2.24;
    weather(lat, long);
  } else if (leeds.checked) {
    var lat = 53.80;
    var long = -1.5491;
    weather(lat, long);
  } else if (london.checked) {
    var lat = 51.5074;
    var long = -0.12;
    weather(lat, long);
  }
}
<form action="">
  <label for="manchester">
      <input type="radio" value="manchester" id="manchester" name="location" checked>Manchester</input>
     </label>
  <label for="leeds">
      <input type="radio" value="leeds" id="leeds" name="location">Leeds</input>
     </label>
  <label for="london">
      <input type="radio" value="london" id="london" name="location">London</input>
     </label>
</form>

如果我手动将每个单选标签更改为“checked="true"”,则以下功能有效,但是我希望这只是在用户单击单选按钮时发生。

标签: javascripthtmlcssradio-button

解决方案


希望这可以帮助:

const manchester = document.querySelector('#manchester')
const leeds = document.querySelector('#leeds')
const london = document.querySelector('#london')
const radios = document.querySelectorAll('input[type=radio]')
for (let i = radios.length; i--;) {
  radios[i].onclick = success;
}

function success(pos) {
  if (manchester.checked) {
    var lat = 53.48;
    var long = -2.24;
    console.log(lat, long);
  } else if (leeds.checked) {
    var lat = 53.80;
    var long = -1.5491;
    console.log(lat, long);
  } else if (london.checked) {
    var lat = 51.5074;
    var long = -0.12;
    console.log(lat, long);
  }
}
<form action="">
  <label for="manchester">
      <input type="radio" value="manchester" id="manchester" name="location" checked>Manchester</input>
     </label>
  <label for="leeds">
      <input type="radio" value="leeds" id="leeds" name="location">Leeds</input>
     </label>
  <label for="london">
      <input type="radio" value="london" id="london" name="location">London</input>
     </label>
</form>

如果有什么不清楚 - 我会解释。


推荐阅读