未捕获的TypeError:无法设置属性' src'为null

时间:2014-05-04 19:16:14

标签: javascript

因此,在尝试为学校编写这段代码时,我一直遇到这个错误。 "未捕获的TypeError:无法设置属性' src' of 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时,它只是给我错误。

1 个答案:

答案 0 :(得分:2)

假设bigPic实际上是img代码的ID,您将需要执行document.getElementById('bigPic')而不是#bigPic

您正在混合使用jQuery或CSS(即$('#bigPic'))的CSS选择器和普通的javascript。使用getElementById功能,您已经说过要通过ID查找内容了。

相关问题