3 回答

TA貢獻1828條經驗 獲得超13個贊
你需要一個事件監聽器
document.getElementById("red").addEventListener("change", myAlert);
function myAlert() {
alert('working');
}
<form>
What color do you prefer?<br>
<input type="radio" name="colors" id="red">Red<br>
<input type="radio" name="colors" id="blue">Blue
</form>

TA貢獻1803條經驗 獲得超3個贊
您需要事件偵聽器 - 不建議使用內聯事件處理程序
您需要決定要測試什么
這里有兩種跑步方式
它們是收音機,所以我們不需要測試它們是否被檢查
window.addEventListener("load",function() { // when the page loads
// testing clicking the RED only
document.getElementById("red").addEventListener("click",function() {
console.log("The specific Red event listener was invoked");
});
// delegation
document.querySelector("form").addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.id==="red") console.log("Clicking in the form, we clicked the thing with ID red")
})
});
<form>
What color do you prefer?<br>
<label><input type="radio" name="colors" id="red">Red</label><br>
<label><input type="radio" name="colors" id="blue">Blue</label>
</form>

TA貢獻1851條經驗 獲得超4個贊
嘗試這樣:
<form>
What color do you prefer?<br>
<input type="radio" name="colors" id="red"/>Red<br>
<input type="radio" name="colors" id="blue"/>Blue
</form>
<script>
document.getElementById("red").onchange = function() {
alert('working');
}
</script>
單擊單選按鈕時需要一個事件處理程序來運行該特定代碼。
添加回答
舉報