为什么我的变量显示为空?
问题描述:
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>
答
- 前
- 这个错误是因为你试图让一个元素早于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>
我认为这与你的脚本标签的位置做。内联脚本一出现就执行,所以链接标记还不存在。尝试将脚本移动到页面底部(正上方末端'