[英]Why does is my onchange event triggered when my page loads instead of when I click my radio button?
I have the following code in my Javascript.我的 Javascript 中有以下代码。 I'd like the alert to happen when a user checks the radio button, but instead it happens when the page loads, and NOTHING happens when the radio button gets checked.
我希望警报在用户选中单选按钮时发生,但在页面加载时发生,而在单选按钮被选中时没有发生任何事情。 Why?
为什么?
var myRadioButton = document.getElementById("myRadioButton");
myRadioButton.onchange=alert("Checked!");
The radio button starts off unchecked.单选按钮开始时未选中。 In the HTML it looks like this:
在 HTML 中,它看起来像这样:
<div class="myRadioButton"><input type="radio" id="myRadioButton" name="radioButtons" /> This is my radio button
</div>
Why on earth would the Javascript think an onchange
event has occurred when the page loads?为什么 Javascript 会认为页面加载时发生了
onchange
事件? And why doesn't it recognize a change when I actually check the radio button?为什么当我实际检查单选按钮时它不识别更改?
In fact, whatever element I use with onchange
makes the alert pop up when the page loads, without any user interaction at all.事实上,我在
onchange
使用的任何元素都会在页面加载时弹出警报,根本不需要任何用户交互。 Am I misunderstanding how onchange
works?我误解了
onchange
工作原理吗?
What you mean to do is你的意思是
myradiobutton.onchange = function() { alert('Checked'); };
What you did will execute the alert
-function and assign the return value of that function as an event handler to the onchange
event (which will do nothing when executed)您所做的将执行
alert
函数并将该函数的返回值作为事件处理程序分配给onchange
事件(执行时将不执行任何操作)
try尝试
<script>
var myRadioButton = document.getElementById("myRadioButton");
myRadioButton.onchange = function () { alert("Checked!") };
</script>
In your code在你的代码中
myradiobutton.onchange = alert('Checked')
You actually called alert function, and assigned its return value as event handler.您实际上调用了警报函数,并将其返回值指定为事件处理程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.