使用javascript点击不同的链接时,不同的图像显示在同一页面中?

时间:2015-07-01 10:11:55

标签: javascript

请改进此代码。如果我们点击图片2链接。图片链接2没有work.i在此代码中也使用了超过2个图像。

from datetime import datetime

def test(self, contracts_list):
    premium_per_month = {}
    for contract in contracts_list:
        dt = datetime.strptime(contract.date_start, self._date_fmt)
        if d.get(dt.month):
            premium_per_month[dt.month][0] += contract.premium
            premium_per_month[dt.month][1].append(contract.id)
        else:
            val_lst = [contract.premium, [contract.id]]
            premium_per_month[dt.month] = val_lst 
    return premium_per_month
<script>
        function changeImage() {
            var image = document.getElementById('myImage');
            var img1 = document.getElementById('1');
            var img2 = document.getElementById('2');
            var img3 = document.getElementById('3');

            if (img1.id == 1 ) {
                image.src = "img/1.jpg";
            } 
            else if (img2.id == 2) {
                image.src = "img/2.jpg";
            }
            else if (img3.id == 3) {
                image.src = "img/3.jpg";
            }
             else
            {
                image.src = "img/5.jpg";
            }

        }
    </script>

1 个答案:

答案 0 :(得分:1)

试用此代码:

<!DOCTYPE html>
<html>
<body>

    <h1>JavaScript Can Change Images</h1>

    <img id="myImage" onclick="changeImage()" src="img/0.jpg" width="180" height="180">
    <table>
        <tr>
            <td > <a href="#" id="1" onclick="changeImage(this.id)"> Image1</a></td>

        </tr>
        <tr>
            <td> <a href="#" id="2"  onclick="changeImage(this.id)"> Image2</a></td>

        </tr>
  <tr>
            <td> <a href="#" id="3"  onclick="changeImage(this.id)"> Image3</a></td>

        </tr>
    </table>

</body>
<script>
        function changeImage(click_id) {
            var image = document.getElementById('myImage');
            var img1 = document.getElementById('1');
            var img2 = document.getElementById('2');
            var img3 = document.getElementById('3');

            if (click_id == 1 ) {
                image.src = "img/1.jpg";
            } 
            else if (click_id == 2) {
                image.src = "img/2.jpg";
            }
            else if (click_id == 3) {
                image.src = "img/3.jpg";
            }
             else
            {
                image.src = "img/5.jpg";
            }

        }
    </script>
</html>