为什么这段代码不能正常工作?

时间:2015-08-24 13:34:05

标签: javascript

在此代码中单击任何单选按钮时,只有image3.jpg显示,在第二次单击时没有任何变化。

var a = document.getElementsByClassName('rbpic');

for (var i = 0 ; i<a.length ; i++) {
    a[i].addEventListener("click" , changepic );
}

function changepic() {
    var c = document.getElementById("image") ;

    for (var j=0 ; j<a.length ; j++)  {   
        var d = a[j].value ;

        if(d === "one") { 
            c.src = "image1.jpg";
        }
        else if (d === "two") { 
            c.src = "image2.jpg";
        }
        else if (d === "three") { 
            c.src = "image3.jpg";
        }
    }
}

2 个答案:

答案 0 :(得分:2)

您的问题在于changepic()功能:您可以循环浏览每个单选按钮,并在任何单选按钮更改时设置相应的图像。

我的两个解决方案:

  1. 摆脱循环并将a[j].value替换为e.target.value

    function changepic(e) {
        var c = document.getElementById("image");
        var d = e.target.value;
        if (d === "one") {
            c.src = "image1.jpg";
        } else if (d === "two") {
            c.src = "image2.jpg";
        } else if (d === "three") {
            c.src = "image3.jpg";
        }
    }
    
  2. 循环浏览所有单选按钮并查看选中的按钮:

    function changepic() {
        var c = document.getElementById("image");
        for (var j = 0; j < a.length; j++) {
            if (a[j].checked) {
                var d = a[j].value;
                if (d === "one") {
                    c.src = "image1.jpg";
                } else if (d === "two") {
                    c.src = "image2.jpg";
                } else if (d === "three") {
                    c.src = "image3.jpg";
                }
            }
        }
    }
    

答案 1 :(得分:1)

要引用在事件处理程序中单击的单选按钮,请使用this

var a = document.getElementsByClassName('rbpic');

for (var i = 0 ; i<a.length ; i++) {
    a[i].addEventListener("click" , changepic );
}

//We declare c on the outside so we're not calling document.getElementById() on every single click:
var c = document.getElementById("image") ;
function changepic() {
    //Get the value of this radio button:
    var d = this.value ;
    //Execute the following as normal:
    if(d === "one") { 
        c.src = "image1.jpg";
    }
    else if (d === "two") { 
        c.src = "image2.jpg";
    }
    else if (d === "three") { 
        c.src = "image3.jpg";
    }
}