javascript - 单击时,我的单选按钮不会更改为选中。我正在尝试使用它来更改显示的内容
问题描述
我正在使用 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"”,则以下功能有效,但是我希望这只是在用户单击单选按钮时发生。
解决方案
希望这可以帮助:
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>
如果有什么不清楚 - 我会解释。
推荐阅读
- c# - 当字段名称是保留关键字(如“short”)时,如何使用 Newtonsoft 反序列化 JSON 对象?
- twilio - 使用 TwiML Bin 的出站 SIP 呼叫:语音配置请求 URL
- c - 如何从 C 中的 STDOUT 读取直到 EOF?
- machine-learning - 使用 Long Short Term Memory[LSTM] 进行文本分类在每次迭代中获得不同的结果
- python - 深拷贝和迭代返回不同的结果
- javascript - 尝试更新可枚举的属性类型时如何更新数据库?
- python - 创建一个包含许多 dicts 的列表
- mysql - mariadb Regexp 有时在存储过程中返回空
- javascript - 错误未在 javascript 中显示状态列
- responsive - NSView 准备内容(在:)