js---点击radio按钮实现图片轮换(two methds)

方法一:

 

<head>
    <title></title>
    <script type="text/javascript">
        function UpdateImg() {
          
            var dogandcat = document.getElementsByName('dogandcat'); //获取所有name=dogandcat的单选按钮
            for (var i = 0; i < dogandcat.length; i++) {
                if (dogandcat[i].checked == true) {
                    var value = dogandcat[i].getAttribute('value');
                    switch (value) {
                        case '2':
                            document.getElementById('img1').setAttribute('src', 'images/2.jpg');
                            break;
                        case '3':
                            document.getElementById('img1').setAttribute('src', 'images/3.jpg');
                            break;
                        case '4':
                            document.getElementById('img1').setAttribute('src', 'images/4.jpg');
                            break;
                        case '6':
                            document.getElementById('img1').setAttribute('src', 'images/6.jpg');
                            break;
                    }
                }
            }
        }
    </script>
</head>
<body>
    <img id="img1" src="images/9.jpg" width="200px" height="200px" />
    <br />
    <input type="button"  value="改变图片" onclick="UpdateImg();" />
    <br />
    <input id="Radio1" name="dogandcat" type="radio" value="2" onclick="UpdateImg();"  />忧伤的小狗
    <input id="Radio2" name="dogandcat" type="radio" value="3" onclick="UpdateImg();"/>卖萌的小狗
    <input id="Radio3" name="dogandcat" type="radio" value="4" onclick="UpdateImg();"/>愤怒的小狗
    <input id="Radio4" name="dogandcat" type="radio" value="6" onclick="UpdateImg();"/>可爱的小猫
</body>

方法二:

 <script type="text/javascript">
        function UpdateImg(radio) {
            //简写方式
            //document.getElementById('img1').setAttribute('src', 'images/' + radio.getAttribute('value') + '.jpg');
            var numb = radio.getAttribute('value');//获取被选中的单选按钮的value值
            document.getElementById('img1').setAttribute('src','images/'+numb+'.jpg');//设置要加载的图片
        }
    </script>
</head>
<body>
<img id="img1" src="images/9.jpg" width="200px" height="200px" />
    <br />
    <input type="button"  value="改变图片" onclick="UpdateImg();" />
    <br />
    <input id="Radio1" name="dogandcat" type="radio" value="2" onclick="UpdateImg(this);"  />忧伤的小狗
    <input id="Radio2" name="dogandcat" type="radio" value="3" onclick="UpdateImg(this);"/>卖萌的小狗
    <input id="Radio3" name="dogandcat" type="radio" value="4" onclick="UpdateImg(this);"/>愤怒的小狗
    <input id="Radio4" name="dogandcat" type="radio" value="6" onclick="UpdateImg(this);"/>可爱的小猫
</body>

 

注释:图片名称为 2.jpg 、3.jpg等。

你可能感兴趣的:(js---点击radio按钮实现图片轮换(two methds))