2017-09-25 3 views
0

私はgetElementById()を使用して、画像に関連付けられている乱数にファビオの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のコンテンツがロードされているよりも、要素を取得しようとしているため、このエラーがある
  2. 前に、あなたの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>

関連する問題