2017-09-25 93 views
0

Heyo!我使用getElementById()將favicon的href修改爲與圖片關聯的隨機數字。但是,每次我這樣做,我嘗試將它分配給它的變量是null我做錯了什麼?爲什麼我的變量顯示爲空?

<!DOCTYPE html> 

<html> 
<head> 
<script type="text/javascript"> 


    var number = Math.floor((Math.random() * 5) + 1); 

    var ico = number + ".ico" 

    document.getElementById("favicon").href = ico <!-- should change the icon --> 

</script> 
<title>Cool Server People!</title> 
<link rel="stylesheet" href="style.css"> 
<link id="favicon" rel="shortcut icon" href="1.ico" /> <!-- should edit this part --> 

</head> 
<body> 
<div class="header"> 
    <h1>Cool Server People</h1> 
</div> 

<div class="space"> 

</div> 

<div class="blog"> 

    <a href="test-post.html" class="post">Blog Post</a> 
    <p>asdfdasdfasdfasdfa</p> 

</div> 

+1

我認爲這與你的腳本標籤的位置做。內聯腳本一出現就執行,所以鏈接標記還不存在。嘗試將腳本移動到頁面底部(正上方末端''標籤。 – solarc

回答

1
  1. 這個錯誤是因爲你試圖讓一個元素早於DOM內容加載請寫下你的JS代碼。而已!

<!DOCTYPE html> 
 

 
<html> 
 
<head> 
 
    <title>Cool Server People!</title> 
 
    <link rel="stylesheet" href="style.css"> 
 
    <link id="favicon" rel="shortcut icon" href="1.ico" /> <!-- should edit this part --> 
 

 
</head> 
 
<body> 
 
<div class="header"> 
 
    <h1>Cool Server People</h1> 
 
</div> 
 

 
<div class="space"> 
 

 
</div> 
 

 
<div class="blog"> 
 

 
    <a href="test-post.html" class="post">Blog Post</a> 
 
    <p>asdfdasdfasdfasdfa</p> 
 

 
    <script type="text/javascript"> 
 
     
 
     var number = Math.floor((Math.random() * 5) + 1); 
 
     var ico = number + ".ico"; 
 
     document.getElementById("favicon").href = ico; <!-- should change the icon --> 
 

 
    </script> 
 

 
</div>