简体   繁体   中英

javascript onclick function not working?

I am trying to do an onclick event where when a light bulb image is clicked it goes from a light bulb off to a light bulb on image and vice versa. I am using an external javascript file. when I click on the image nothing happens.

I cant figure out whats wrong,

my html portion:

<head>
    <link rel="stylesheet" href="css/program-01.css" />
    <script type="text/javascript" src="javascript/program-01.js"></script>
    <title>
        <h1>Program-01</h1>
    </title>
</head>

<body>
    <div id="LightOff">
        <img src="images/light_off.png" id="light_off" alt="" onclick="LightBulbFunction()" />
    </div>
</body>

my js file function:

function LightBulb() {
    var image_change = document.getElementById("light_off");

    if (image_change.src == "images/light_off.png") {
        image_change = "images/light_on.png";
    } else {
        image_change = "images/light_off.png";
    }
}

Suggestions/Problems:

  1. You function names are different.

    You're using the function LightBulbFunction on the onclick event. But, you don't have the function of that name in your script. You'll get

ReferenceError: LightBulbFunction() is not defined.

  1. To change the image src attribute value, use image_change.src inside the event handler.

To solve the problem change the name of onclick attribute value to LightBulb .

 function LightBulb() { var image_change = document.getElementById("light_off"); if (image_change.src == "images/light_off.png") { image_change.src = "images/light_on.png"; // ^^^^ } else { image_change.src = "images/light_off.png"; // ^^^^ } } 
 <div id="LightOff"> <img src="images/light_off.png" id="light_off" alt="" onclick="LightBulb()" /> <!-- ^^^^^^^^^^^ --> </div> 

Better approach will be to use addEventListener to bind events on the elements.

 document.getElementById('light_off').addEventListener('click', function() { var image_change = document.getElementById("light_off"); if (image_change.src == "images/light_off.png") { image_change.src = "images/light_on.png"; } else { image_change.src = "images/light_off.png"; } }, false); 
 <div id="LightOff"> <img src="images/light_off.png" id="light_off" alt="" onclick="LightBulb()" /> <!-- ^^^^^^^^^^^ --> </div> 

Well in your html, the code is onclick="LightBulbFunction()" while in javascript it is LightBulb . Change either of them and make them match

You are not redefining the .src . Change

image_change =

to

image_change.src =

And your function needs to have the same LightBulb function name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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