问题描述
我想要的是,当我单击特定的红色 id单选按钮时,它向我显示了 Alert ,正如您在代码中看到的那样……在我的情况下,它不是发生了什么。问题是什么,该如何解决?
解决方法
您需要一个eventListener
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>
,
- 您需要事件监听器-不建议使用内联事件处理程序
- 您需要确定要测试的内容
有两种运行方式
它们是收音机,所以我们不需要测试它们是否被检查
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>
,
尝试这样:
<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>
单击单选按钮时,需要事件处理程序来运行该特定代码。