因此,在尝试为学校编写这段代码时,我一直遇到这个错误。
“未捕获的TypeError:无法将属性'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(即$('#bigPic')
)中使用的CSS选择器与普通javascript混合在一起。使用getElementById
函数,您已经在说要通过ID查找内容。