举个小例子。我可能遗漏了一些基本的东西,我已经有一段时间没有使用 javascript 了。
我的问题是我收到错误(在 Chrome 开发者工具中):“Uncaught TypeError: Cannot set property 'src' of null at Image.image1.onload (index.html:15)”
这似乎是一个直截了当的错误。但是,我相信由于 $(document).ready(function(){imageA();});
,调用时应该已经加载了文档。所以我不知道为什么它找不到元素#image_holder
。
这是一个非常小的例子:
<!DOCTYPE>
<html>
<head>
<title>Image Quiz</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var imageASelection = 1;
/* ImageA */
function imageA() {
var image1 = new Image();
image1.onload = function() {
document.getElementById('image_holder').src = this.src;
}
image1.src="images/ImageA.jpg";
$('html, body, #map').html('\
<map name="image-map">\
<area onclick="imageAOption1();" coords="827,1305,297,795" shape="rect">\
<area onclick="imageAOption2();" coords="1361,1307,839,800" shape="rect">\
<area onclick="imageAOption3();" coords="1370,792,1888,1300" shape="rect">\
<area onclick="imageAOption4();" coords="1895,788,2431,1305" shape="rect">\
<area onclick="imageANext();" coords="2431,1640,2146,1479" shape="rect">\
</map>');
}
function imageAOption1() {
imageASelection = 1;
}
function imageAOption2() {
imageASelection = 2;
}
function imageAOption3() {
imageASelection = 3;
}
function imageAOption4() {
imageASelection = 4;
}
function imageANext() {
imageB();
}
$(document).ready(function() {
imageA();
})
</script>
</head>
<body>
<img id="image_holder" usemap="#image-map">
<div id="map"></div>
</body>
</html>
感谢您的帮助!
如果你想知道我想做什么。我正在尝试在后台加载图像。我会有多个图像,但我不想看到闪烁。所以我试图在后台加载图像。如果我做错了,请告诉我。
谢谢!
最佳答案
当你做的时候
$('html, body, #map').html('\
<map name="image-map">\
<area onclick="imageAOption1();" coords="827,1305,297,795" shape="rect">\
<area onclick="imageAOption2();" coords="1361,1307,839,800" shape="rect">\
<area onclick="imageAOption3();" coords="1370,792,1888,1300" shape="rect">\
<area onclick="imageAOption4();" coords="1895,788,2431,1305" shape="rect">\
<area onclick="imageANext();" coords="2431,1640,2146,1479" shape="rect">\
</map>');
你覆盖了整个 body ,替换了你的形象;加载图像时,它不在文档中。
也许您想替换 #map
而不是整个主体?
那么您应该通过 $('#map')
或 $('html body #map')
查找它,不带逗号。
关于javascript - 在调用 $(document).ready(function() { ... }) 之后,为什么我的 document.getElementById 调用为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55308962/