簡體   English   中英

無法讀取屬性“ parentNode”

[英]Cannot read property 'parentNode'

我開始學習JavaScript,但我一生都無法弄清楚,為什么這個“無法讀取屬性” parentNode”在控制台中被拋出;為什么? 以及為什么for循環在第三個鏈接之后調用一個。

我正在上一堂關於javascript轉換的課程,轉換有效,但是為什么會引發錯誤?

<style type="text/css" media="screen">
  #caption, #content {
    width: 30%;
    float: left;
    padding: 10%;
    line-height: 1.675em;
  }
</style>

<script type="text/javascript" charset="utf-8">
  window.onload = initRollover;

  function initRollover() {
    for (var i = 0; i < document.links.length; i++) {  
      console.log(i);  
      if(document.images[i].parentNode.tagName == "A") {
        setupRollover(document.images[i]);
      } 
      document.links[i].setAttribute('class', 'test');
    }
  }

  function setupRollover(thisImage){
    thisImage.outImage = new Image();
    thisImage.outImage.src = thisImage.src;
    thisImage.onmouseout = function() {
      this.src = this.outImage.src;
    }

    thisImage.overImage = new Image();
    thisImage.overImage.src = "images/" + "silver" + ".jpg";
    thisImage.onmouseover = function(){
      this.src = this.overImage.src;
    }
  }
</script>

<div id="content" style="background: lightgreen;">
  <img src="images/silver.jpg" width="240" alt="Silver" id="photoA">
  <br><br>
  <a href="boom.html">
    <img src="images/gold.jpg" width="240" alt="Gold" id="photoB">
  </a>
</div>
<div id="caption">
  <a href="foo.html">Lorem ipsum dolor sit amet,</a> consectetur adipisicing elit, sed do eiusmod
  tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
  quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
  consequat. <a href="bar.html">Duis aute irure dolor </a>in reprehenderit in voluptate velit esse
  cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
  proident, sunt in <a href="car.html">culpa qui officia deserunt</a> mollit anim id est laborum.
</div>
<div style="clear:both"></div>

謝謝

對於您要實現的目標,我不確定。 但是我看到的問題在這里

function initRollover() {
for (var i = 0; i < document.links.length; i++) {  
  console.log(i);  
  if(document.images[i].parentNode.tagName == "A") {
    setupRollover(document.images[i]);
  } 
  document.links[i].setAttribute('class', 'test');
}
}

在您的html代碼中,有3個帶標簽的鏈接,但只有2個帶標簽的圖像。 因此,當i = 2時,沒有document.images [2]。 因此parentNode為null。 那會導致你的錯誤。

希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM