未捕获的参考错误:图像未定义

时间:2015-08-11 13:38:36

标签: javascript

当我在谷歌浏览器(或任何其他浏览器)中运行时,我收到错误     未捕获的ReferenceError:图像未定义

以下是代码:

<!doctype html>
<head>
<style>
body {background-color:lightgrey}
</style>
<title>Play Pixel Draw</title>
<h1>Pixel Draw!</h1>
</head>
<body>
<p>Click on the white squares to change that square blue. Make whatever you want!</p>
<hr>
<img id="first" onclick="changeImage()" src="square1.png" width="50" height="50">
<script src="script.js"></script>
</body>
</html>

使用Javascript:

function changeImage() {
var square = document.getElementById('first');
if (image.src.match("square1.png")) {
    image.src = "squareblue1.jpg";
} else {
    image.src = "square1.png";
}
}

假设所有图片都在正确的位置,我该如何解决?

1 个答案:

答案 0 :(得分:0)

下面的代码中没有引用image变量 - 正如错误所暗示的那样,未定义。

function changeImage() {
    var square = document.getElementById('first');
    if (image.src.match("square1.png")) {
        image.src = "squareblue1.jpg";
    } else {
        image.src = "square1.png";
    }
}

我想要做的就是将方形变量更改为图像,我假设。

function changeImage() {
    var image = document.getElementById('first');
    if (image.src.match("square1.png")) {
        image.src = "squareblue1.jpg";
    } else {
        image.src = "square1.png";
    }
}