簡體   English   中英

單擊時,我的單選按鈕不會更改為“已檢查”。 我正在嘗試使用它來更改顯示的內容

[英]My radio buttons don't change to Checked when clicked. I'm trying to use this to change the content displayed

我正在使用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> 

如果有不清楚的地方-我會解釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM