我无法在函数中找出原因,只有当四个第一个单选按钮的(radioBtn.checked)传递if时。当我记录其他人时,他们仍然需要时检查,但if似乎不起作用。这就是我所说的:
var input = document.getElementsByName("focus");
for(var i = 0; i<input.length; i++) {
input[i].addEventListener("change", function(){
getCheckedRadioValue("focus");
}, false);
}
function getCheckedRadioValue(radioGroupName) {
var rads = document.getElementsByName(radioGroupName),
i;
this.value = 0;
for (i=0; i < rads.length; i++) {
console.log(rads[3].checked);
if (rads[i].checked){
this.value = rads[i].value;
console.log(this.value);
return rads[i].value
}
return {
value: this.value
}
}
}
document.addEventListener('keydown', function (event) {
if (event.keyCode == 38) {
console.log(value);
switch (value) {
case "car": car.accelerate(); break;
case "boat": boat.accelerate(); break;
case "aircraft": aircraft.accelerate(); break;
case "amphibia": console.log("amphibia"); break;
default: console.log("Nothing is checked!"); break;
}
}
});
Here就是jsfiddle中的一切。
答案 0 :(得分:3)
在for循环的第一次迭代后返回一个值。只需在for-loop之外移动默认返回值,如下所示:
function getCheckedRadioValue(radioGroupName) {
var rads = document.getElementsByName(radioGroupName), i;
this.value = 0;
for (i = 0; i < rads.length; i++) {
if (rads[i].checked) {
this.value = rads[i].value;
return rads[i].value
}
}
return {
value: this.value
}
}