[英]I have an image slideshow on my homepage but when I go to other page it throws an error
我有一个网站页面和图片幻灯片:
<div className="recommended" id="bluelakes">
<p className="greeting-text">We also recommend you visiting <span>Blue Lakes</span>:</p>
<div className="recommended-brief">
<div className="description">
<p>
<span className="dark">Ecological trail "<span>Blue Lakes</span>"</span>
<br/>
<br/>
is located on the territory of the Narochansky National Park in the Myadel district, 500 m beyond the village of Olshevo.
<br/>
<br/>
Each time you come to this amazing place, you will discover something new, this is a unique hilly-lake complex with vast forests, an abundance of springs and truly unique lakes.
</p>
</div>
<div className="carousel">
<div className="carousel-item first">
<img id="slide" alt="slide"/>
</div>
</div>
<div className="more">
<a href="/" className="see-more">See more...</a>
</div>
</div>
</div>
它看起来像这样:
这是幻灯片脚本本身:
import bluelakesFirst from '../media/images/BlueLakes/BlueLakes1.jpg'
import bluelakesSecond from '../media/images/BlueLakes/BlueLakes2.jpg'
import bluelakesThird from '../media/images/BlueLakes/BlueLakes3.jpg'
import bluelakesFourth from '../media/images/BlueLakes/BlueLakes4.jpg'
let n = 0;
let images = [];
images[0] = bluelakesFirst
images[1] = bluelakesSecond
images[2] = bluelakesThird
images[3] = bluelakesFourth
let switchImage = () => {
document.getElementById('slide').src = images[n]
if (n < images.length - 1) {
n++;
} else {
n = 0;
}
setTimeout(switchImage, 3000);
}
window.onload = switchImage
它工作正常,但是当我 go 到关于我们页面或任何其他页面时,它会抛出错误:
TypeError: Cannot set property 'src' of null
switchImage
D:/trail.by/src/scripts/carousel.js:15
12 | images[3] = bluelakesFourth
13 |
14 | let switchImage = () => {
> 15 | document.getElementById('slide').src = images[n]
16 |
17 | if (n < images.length - 1) {
18 | n++;
我理解是这样,可能是因为其他页面没有这个ID的元素,但我也没有在其他页面上导入这个脚本。
只需将该代码片段包装在if
语句中即可。
if(document.getElementById('slide') !== null) {
document.getElementById('slide').src = images[n]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.