gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot set property 'src' of null

转载 作者:行者123 更新时间:2023-12-02 17:26:27 24 4
gpt4 key购买 nike

因此,在尝试为学校编写这段代码时,我不断遇到此错误。“未捕获的类型错误:无法将属性'src'设置为null” 本质上我想做的是仅在JS中,允许用户将鼠标悬停在缩略图大小的图片上并将主图片更改为相应的缩略图。

 var ImageGallery = {
init: function(){
picArray = ["1", "2", "3", "4"];

// Get reference to large image and store in variable named canvas
ImageGallery.canvas = document.getElementById("#bigPic");

// Set up nodelist, named thumbs, containing references to all
// <img> tags in div#thumbnails
var thumbs = document.querySelectorAll('#thumbnails > img');

// Add mouseover and mouseout event handlers to each thumbnail
// image using a for loop. Set them up to call a method of our
// object called newPic on mouse over and a method called origPic
// on mouse off.

for(var index = 0; index < thumbs.length; index++){
thumbs[index].onmouseover = ImageGallery.newPic;
thumbs[index].onmouseout = ImageGallery.origPic;
console.log(index);
}},
newPic: function(){
// Get the value of the moused over object's id attribute and
// store it in a variable named imgNumber
var imgNumber = this.getAttribute('id');


// Build the path to the image we want to rollover to and store
// the path string in a variable named imgPath
var imgPath = "images/bigPics/" + (parseInt(imgNumber) + 1) + ".jpg";
//alert(imgPath);

// Rollover the large image to the moused over thumbnail's large
// image
bigPic = document.getElementById('#bigPic');
bigPic.src = imgPath;
},
origPic: function(){
}
};

Core.start(ImageGallery);

当我使用警报来验证它是否有效时,我可以显示 imgPath,但是当我尝试设置主 div#bigPic 的 src 时,它只会给我错误。

最佳答案

假设 bigPic 实际上是 img 标签的 ID,您需要执行 document.getElementById('bigPic') 而不是使用 #bigPic

您将在 jQuery 或 CSS 中使用的 CSS 选择器(即 $('#bigPic'))与纯 JavaScript 混合在一起。使用 getElementById 函数,您已经表示您正在通过 ID 查找某些内容。

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

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