错误:无法在 Img 字段中将属性“src”设置为 null
2020-06-05
91
我正在使用 JavaScript 创建图像滑块。
我将 图像 URL 放入数组中,然后使用 javascript 函数 滑动图像。
var imageurls = ["https://s3-ap-southeast-1.amazonaws.com/he-public-data/Avengers3c9095c4.jpg",
"https://s3-ap-southeast-1.amazonaws.com/he-public-data/Avengers1dde2dff.jpg",
"https://s3-ap-southeast-1.amazonaws.com/he-public-data/Avengers2f856ebb.jpg.",
"https://s3-ap-southeast-1.amazonaws.com/he-public-data/Avengers40b07bc7.jpg",
"https://s3-ap-southeast-1.amazonaws.com/he-public-data/Avengers51fd2ccc.jpg"];
var index=0;
document.getElementById("demo").src = imageurls[index];
function nextSlider(){
index++;
if(index>4){
index=4;
}
document.getElementById("demo").src = imageurls[index];
}
function prevSlider() {
index--;
if(index<0){
index=0;
}
document.getElementById("demo").src = imageurls[index];
}
<!DOCTYPE>
<html>
<head>
<title>Avengers Avenue</title>
<link rel="stylesheet" href="css/main.css">
<script src="js/main.js"></script>
</head>
<body>
<h1>Avengers Avenue</h1>
<div class="img-field">
<a class="prev" onclick="prevSlider()">❮</a>
<img id= "demo">
<a class="next" onclick="nextSlider()">❯</a>
</div>
</body>
</html>
现在我收到此错误:
ma​​in.js:4 Uncaught TypeError: Cannot set property 'src' of null at main.js:4
我不知道如何解决?或者我在哪里犯了错误?
2个回答
我将您的问题编辑为一个片段,它完美地工作了。
因此,在加载
html
元素之前,最好先加载
javascript
。
在这种情况下,您的
javascript
无法找到元素,因此它是
src
。
解决方案
将您的
javascript
放在
<body>
末尾之前,如下所示:
<!DOCTYPE html>
<html lang="en">
<body>
<!-- your html...-->
<script src="yourJS.js"></script>
</body>
</html>
Tim567
2020-06-05
在 . 标签结束之前添加 javascript 文件
var imageurls = [
'https://s3-ap-southeast-1.amazonaws.com/he-public-data/Avengers3c9095c4.jpg',
'https://s3-ap-southeast-1.amazonaws.com/he-public-data/Avengers1dde2dff.jpg',
'https://s3-ap-southeast-1.amazonaws.com/he-public-data/Avengers2f856ebb.jpg.',
'https://s3-ap-southeast-1.amazonaws.com/he-public-data/Avengers40b07bc7.jpg',
'https://s3-ap-southeast-1.amazonaws.com/he-public-data/Avengers51fd2ccc.jpg'
]
var index = 0
document.getElementById('demo').src = imageurls[index]
function nextSlider () {
index++
if (index > 4) {
index = 4
}
document.getElementById('demo').src = imageurls[index]
}
function prevSlider () {
index--
if (index < 0) {
index = 0
}
document.getElementById('demo').src = imageurls[index]
}
<!DOCTYPE>
<html>
<head>
<title>Avengers Avenue</title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<h1>Avengers Avenue</h1>
<div class="img-field">
<a class="prev" onclick="prevSlider()">❮</a>
<img id= "demo">
<a class="next" onclick="nextSlider()">❯</a>
</div>
<script src="js/main.js"></script> /* include here */
</body>
</html>
Himanshu Pandey
2020-06-05