为什么我的变量显示为null?

时间:2017-09-25 23:39:29

标签: javascript html favicon

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 个答案:

答案 0 :(得分:1)

  1. 请将您的JS代码放在
  2. 之前
  3. 此错误是因为您尝试获取早于DOM内容已加载的元素。就是这样!
  4. <!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>