gpt4 book ai didi

javascript - 图像交换——未捕获的类型错误 : Cannot set property 'src' of null

转载 作者:行者123 更新时间:2023-12-02 21:44:26 25 4
gpt4 key购买 nike

我正在学习类(class)的教科书,就像我通常练习的那样。我目前正在开发一个图像交换页面,点击缩略图即可“交换”主图像。单击时图像会放大,就像指向另一个网页的链接一样。我的代码与书中的完全一样,但出现错误。代码是:

var $ = function(id){
return document.getElementById(id);
};

window.onload = function(){
var listNode = $("image_list");
var captionNode = $("caption");
var imageNode = $("main_image");

var imageLinks = listNode.getElementsByTagName("a");

// process image links
var i, image, linkNode, link;
for (i = 0; i < imageLinks.length; i++){
linkNode = imageLinks[i];

// preload image
image = new Image();
image.src = linkNode.getAttribute("href");

// attach event handler
linkNode.onclick = function(evt){
link = this; // "this" is the link that was clicked

// set new image and caption
// the image selected is the "href" and the caption is the title of each image link
imageNode.src = link.getAttribute("href");
captionNode.firstChild.nodeValue = link.getAttribute("title");

// cancel the default action of the event
if (!evt){
evt = window.event;
}
if (evt.preventDefault){
evt.preventDefault();
}else{
evt.returnFalse = false;
}
};
}
// set focus on first image link
imageLinks[0].focus();

};`

错误发生在imageNode.src = link.getAttribute("href");我的 HTML 是:

<body>
<h1>Image Swap With JavaScript</h1>
<p>Click on an image to enlarge.</p>
<ul id="image_list">
<li><a href="images/photo1.jpg" title="Golden Gate">
<img src="thumbnails/thumb1.jpg" alt=""></a></li>
<li><a href="images/photo2.jpg" title="Rocky Coast">
<img src="thumbnails/thumb2.jpg" alt=""></a></li>
<li><a href="images/photo3.jpg" title="Ocean Side">
<img src="thumbnails/thumb3.jpg" alt=""></a></li>
</ul>
<h2 id="caption">Ocean Side</h2>
<p><img id="main-image" src="images/photo3.jpg" alt=""></p>
</body>

为什么我会收到此错误?

最佳答案

先回答,然后讲授...您代码中的错误是,

<p><img id="main-image" src="images/photo3.jpg" alt=""></p> // from html
var imageNode = $("main_image"); // from javascript

id 不匹配,这是一个简单的拼写错误,main_image (never equals) main-image

要么使用 <p><img id="main-image" src="images/photo3.jpg" alt=""></p> // from html
var imageNode = $("main-image"); // from javascript

<p><img id="main_image" src="images/photo3.jpg" alt=""></p> // from html
var imageNode = $("main_image"); // from javascript

现在要了解此类拼写错误,请注意您的代码和变量...快乐编码:)

关于javascript - 图像交换——未捕获的类型错误 : Cannot set property 'src' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60293417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com