【发布时间】:2010-09-24 20:49:38
【问题描述】:
我需要一个单选按钮的事件触发器,以便在另一个按钮被选中时取消选中它。
下面的代码应该可以证明我的困境。
如果您会注意到,html 代码中的每个单选按钮和复选框都附加了一个 onchange 事件触发器。理论上,从选中状态变为未选中状态应该触发 onchange 事件。
复选框会按预期发生。如果您选中一个,您会收到警报,“您的项目已更改为已选中”。如果您取消选中它,您会收到警报“您的项目已更改为未选中”。
使用单选按钮,当您选中第一个按钮时,您会如预期的那样收到警报,“您的项目已更改为选中”,因为该按钮从未选中变为选中。但是,当您选中第二个按钮并且第一个单选按钮从选中更改为未选中时,不会触发“onchange”事件触发器并且不会触发“else”警报。
所以对我来说这个问题是当一个单选按钮被另一个被选中的按钮取消选中时会触发什么事件?
感谢大家对此提供的帮助。
--凯诺利
<html>
<head>
<title></title>
<script type="text/javascript">
function clickAction() {
//alert ('Your item changed');
if (this.checked == true) {alert ('Your item is changed to checked');}
else if (this.checked == false) {alert('Your item is changed to unchecked');}
}
</script>
<script type="text/javascript">
function initializeToggles() {
var button1= document.getElementById('button1');
button1.onchange = clickAction;
var box1= document.getElementById('box1');
box1.onchange = clickAction;
var box2= document.getElementById('box2');
box2.onchange = clickAction;
}
</script>
<script type="text/javascript">window.onload = initializeToggles;</script>
</head>
<body>
<input type="radio" name="testRadio" id="button1" >Button one<br/>
<input type="radio" name="testRadio" id="button2" >Button two<br/><br/>
<input type="checkbox" name="testCheckbox" id="box1" >Box one<br/>
<input type="checkbox" name="testCheckbox" id="box2" >Box two<br/><br/>
</body>
</html>
【问题讨论】:
标签: javascript