多个 ID 在我使用 HTML #1 时工作正常,但在我使用 HTML #2 时不起作用。Chrome 网络控制台显示
>> "Uncaught TypeError: Cannot call method 'setAttribute' of null ".
在 html#2 我删除了
<div id="0001"><a href="#"">LOGIN</a></div>
,并且浏览器不再工作。
HTML #1
<html>
<head>
<title>Index</title>
</head>
<body>
<div id="0001"><a href="#"">LOGIN</a></div>
<div id="0002"><a href="#"">GO</a></div>
<div id="0003"><a href="#"">VISIT</a></div>
<div id="0004"><a href="#"">EXPLORE</a></div>
<div id="0005"><a href="#"">FUNNY PICS</a></div>
<script>
var element = document.getElementById("0001");
element.setAttribute('onclick', 'window.location.href=\'http://site.com/1.html\'');
var element = document.getElementById("0002");
element.setAttribute('onclick', 'window.location.href=\'http://site.com/2.html\'');
var element = document.getElementById("0003");
element.setAttribute('onclick', 'window.location.href=\'http://site.com/3.html\'');
var element = document.getElementById("0004");
element.setAttribute('onclick', 'window.location.href=\'http://site.com/4.html\'');
var element = document.getElementById("0005");
element.setAttribute('onclick', 'window.location.href=\'http://site.com/5.html\'');
</script>
</body>
</html>
HTML #2
<html>
<head>
<title>Index</title>
</head>
<body>
<div id="0002"><a href="#"">GO</a></div>
<div id="0003"><a href="#"">VISIT</a></div>
<div id="0004"><a href="#"">EXPLORE</a></div>
<div id="0005"><a href="#"">FUNNY PICS</a></div>
<script>
var element = document.getElementById("0001");
element.setAttribute('onclick', 'window.location.href=\'http://site.com/1.html\'');
var element = document.getElementById("0002");
element.setAttribute('onclick', 'window.location.href=\'http://site.com/2.html\'');
var element = document.getElementById("0003");
element.setAttribute('onclick', 'window.location.href=\'http://site.com/3.html\'');
var element = document.getElementById("0004");
element.setAttribute('onclick', 'window.location.href=\'http://site.com/4.html\'');
var element = document.getElementById("0005");
element.setAttribute('onclick', 'window.location.href=\'http://site.com/5.html\'');
</script>
</body>
</html>