点击使用2个功能更改图像

时间:2017-11-12 23:27:37

标签: javascript image function click event-listener

Can someone see where Im goin wrong with this code? using two functions to swap out an image

    <button onclick="bulbOn();">Turn the lights On</button>
    <img id="myImage" src="http://i.imgur.com/8kGmXwB.png" alt="Light Bulb">
    <button onclick="bulbOff();">Turn the lights off</button>


   function bulbOn(){
   var el = document.getElementById('myImage');
   el.addEventListener('click', function(){
   this.src = 'http://i.imgur.com/2IRs7Bs.gif';
   });

}

    function.bulbOff(){
    var el = document.getElementById('myImage');
    el.addEventListener('click', function(){
    this.src = 'http://i.imgur.com/8kGmXwB.png';
    });
    }

1 个答案:

答案 0 :(得分:0)

您应该向文档添加事件侦听器。试试这个:

function bulbOn() {
    var el = document.getElementById('myImage');
    document.addEventListener('click', function() {
        el.src = 'http://i.imgur.com/2IRs7Bs.gif';
    });
}
function bulbOff() {
    var el = document.getElementById('myImage');
    document.addEventListener('click', function(){
        el.src = 'http://i.imgur.com/8kGmXwB.png';
    });
}

实际上,不需要变量el。所以:

function bulbOn() {
    document.addEventListener('click', function() {
        document.getElementById('myImage').src = 'http://i.imgur.com/2IRs7Bs.gif';
    });
}
function bulbOff() {
    document.addEventListener('click', function(){
        document.getElementById('myImage').src = 'http://i.imgur.com/8kGmXwB.png';
    });
}