未捕获的TypeError:无法设置null的属性'src' [英] Uncaught TypeError: Cannot set property 'src' of null
问题描述
因此,在尝试为学校编写这段代码时,我一直遇到这个错误。
Uncaught TypeError:无法设置属性'src'为null基本上我要做的只是在JS中,允许用户将鼠标悬停在缩略图大小的图片上并让它将主图片更改为相应的缩略图。
So while trying to work on this piece of code for school I keep running into this error. "Uncaught TypeError: Cannot set property 'src' of null" Essentially what I'm trying to do is in JS only, allow the user to hover over the thumbnail size picture and have it change the main picture to the corresponding thumbnail.
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时,它只是给我错误。
I can get the imgPath to show up when I'm using the alert to verify it works, but when I try to set the src of the main div#bigPic it just gives me the error.
推荐答案
假设 bigPic
实际上是<$的ID c $ c> img 标签,您将要执行 document.getElementById('bigPic')
而不是使用 #bigPic
。
Assuming that bigPic
is in fact the ID of an img
tag, you are going to want to do document.getElementById('bigPic')
instead of using #bigPic
.
您正在混合您在jQuery或CSS中使用的CSS选择器(即 $('#bigPic')
)使用普通的javascript。使用 getElementById
函数,您已经说过要按ID查找内容了。
You are mixing the CSS selector that you'd use in jQuery or CSS (i.e., $('#bigPic')
) with plain javascript. Using the getElementById
function, you're already saying you're looking for something by the ID.
这篇关于未捕获的TypeError:无法设置null的属性'src'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!