2013-11-03 106 views
0

我開始學習JavaScript了,我無法弄清楚我的生活,爲什麼這個'無法讀取屬性'parentNode''正在拋出控制檯;以及爲什麼for循環在第三個鏈接之後調用。無法讀取屬性'parentNode'

我正在關於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> 

感謝

+0

您正在循環訪問'document.links',但在循環中使用了'document.images [i]'。所以如果你有更多的鏈接比你做圖像,你會得到錯誤。 – nnnnnn

回答

1

我不完全相信,以你想要達到的目的。但我看到的問題是這裏

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個帶標籤的圖像。所以當我= 2時,沒有document.images [2]。因此,parentNode爲空。這會導致你的錯誤。

希望有幫助。

+0

我試圖運行一個For循環來查找總共有多少個鏈接(4),然後將任何帶有圖像的鏈接作爲子目標,或者如果有任何帶有父鏈接的圖像,則以該目標爲目標。我只是看到爲什麼If語句導致錯誤,導致如果沒有鏈接父圖像,那麼它不會被跳過? – Brett

+0

噢好吧。我現在明白了。所以問題在於當你使用document.links和document.images時,你正在把它們全部計算在內。有兩種方法可以處理這個問題:1.您可以使用自己的方式。但是你必須在try ... catch塊中包含整個語句。在父鏈接不存在的情況下處理錯誤。 2.更簡單的方法是查看每個鏈接的innerHtml並在其中搜索圖像。 乾杯! –

+0

啊,好吧。這可能更有意義。謝謝。 – Brett