简体   繁体   English

只有第一个单选按钮的属性检查才能正常工作

[英]Only property checked of first radio button works correctly

I am not able to find out why in a function, only if(radioBtn.checked) of the first radio button out of four passes the if.我无法找出函数中的原因,只有四个单选按钮中的第一个单选按钮的if(radioBtn.checked)通过 if。 When I log the others, they are still checked when they need to, but the if doesn't seem to work.当我记录其他人时,他们仍然会在需要时检查,但 if 似乎不起作用。 Here is what I am talking about:这就是我要说的:

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 is everything in jsfiddle.是jsfiddle中的所有内容。

You return a value after the first iteration of the for-loop.在 for 循环的第一次迭代后返回一个值。 Simply move the default return outside the for-loop like this:简单地将默认返回移到 for 循环之外,如下所示:

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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM