我有这段代码,它可以正常使用,但是在document.myform.onchange
的第一时刻我尝试了document.myform.elem.onclick
,而这最后一段代码并不想工作,只有当我把它放在一个表格,它为什么会发生?
<form name="myform">
<input type="radio" name="car" value="audi">audi<br>
<input type="radio" name="car" value="bmw">bmw
<div id="text">some text is here</div>
</form>
function ready() {
var elem = document.getElementsByName("car");
var hid = document.getElementById("text");
var i;
document.myform.onchange = function() {
for (i = 0; i < elem.length; i++) {
if (elem[0].checked == true) {
hid.style.display = "none";
} else {
hid.style.display = "block";
}
}
}
}
document.addEventListener("DOMContentLoaded", ready);
答案 0 :(得分:1)
嗨,你可以从这些例子中获得启发,祝你好运
<form name="myForm">
<input type="radio" name="car" value="1" />
<input type="radio" name="car" value="2" />
</form>
<script>
var rad = document.myForm.car;
var prev = null;
for(var i = 0; i < rad.length; i++) {
rad[i].onclick = function() {
(prev)? console.log(prev.value):null;
if(this !== prev) {
prev = this;
}
console.log(this.value)
};
}
</script>
答案 1 :(得分:1)
change
按钮(循环中)注册radio
个事件而不是form
index
的{{1}}。
radio-input
&#13;
function ready() {
var elem = document.getElementsByName("car");
var hid = document.getElementById("text");
for (var i = 0; i < elem.length; i++) {
elem[i].onchange = function() {
if (this.value === 'audi') {
hid.style.display = "none";
} else {
hid.style.display = "block";
}
}
}
}
document.addEventListener("DOMContentLoaded", ready);
&#13;
答案 2 :(得分:0)
您可以将change
事件附加到您的广播输入中,如下所示:
function ready() {
var radioInputs = document.myform.car,
hid = document.getElementById("text");
for(var i = 0; i < radioInputs.length; i++){
radioInputs[i].onchange = function() {
hid.style.display = radioInputs[0].checked ? 'block' : 'none';
};
}
}
document.addEventListener("DOMContentLoaded", ready);
function ready() {
var radioInputs = document.myform.car,
hid = document.getElementById("text");
for(var i = 0; i < radioInputs.length; i++){
radioInputs[i].onchange = function() {
hid.style.display = radioInputs[0].checked ? 'block' : 'none';
};
}
}
document.addEventListener("DOMContentLoaded", ready);
&#13;
<form name="myform">
<input type="radio" name="car" value="audi">audi<br>
<input type="radio" name="car" value="bmw">bmw
<div id="text">some text is here</div>
</form>
&#13;