[英]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. 我试图做一个onclick事件,当单击灯泡图像时,它会从灯泡熄灭到图像上的灯泡,反之亦然。 I am using an external javascript file.
我正在使用外部javascript文件。 when I click on the image nothing happens.
当我单击图像时,没有任何反应。
I cant figure out whats wrong, 我不知道怎么了
my html portion: 我的html部分:
<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: 我的js文件功能:
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: 建议/问题:
You function names are different. 您的函数名称不同。
You're using the function LightBulbFunction
on the onclick
event. 您正在
onclick
事件上使用函数LightBulbFunction
。 But, you don't have the function of that name in your script. 但是,您的脚本中没有该名称的功能。 You'll get
你会得到
ReferenceError: LightBulbFunction() is not defined.
ReferenceError:未定义LightBulbFunction()。
src
attribute value, use image_change.src
inside the event handler. src
属性值, image_change.src
在事件处理程序内使用image_change.src
。 To solve the problem change the name of onclick
attribute value to LightBulb
. 要解决该问题,
LightBulb
onclick
属性值的名称更改为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. 更好的方法是使用
addEventListener
绑定元素上的事件。
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
. 在您的html中,代码为
onclick="LightBulbFunction()"
而在javascript中,代码为LightBulb
。 Change either of them and make them match 更改它们中的任何一个并使它们匹配
You are not redefining the .src
. 您没有重新定义
.src
。 Change 更改
image_change =
to 至
image_change.src =
And your function needs to have the same LightBulb
function name. 并且您的函数需要具有相同的
LightBulb
函数名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.