我正在努力让这些代码工作,我不能为我的生活理解为什么它不会。我已经尝试过JSlint和一切。对不起新手问题,我用JavaScript花了不到2个小时,所以这是一个愚蠢的问题。感谢。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="Style/demo.css" />
<script type="text/javascript">
window.onload = init;
function init() {
document.getElementById("s1").onclick = print(1);
document.getElementById("s2").onclick = print(2);
document.getElementById("s3").onclick = print(3);
document.getElementById("s4").onclick = print(0);
}
function print(printno) {
var demo = document.getElementById("demo");
switch(printno)
{
case 1:
demo.innerHTML= "It is a period of civil war. Rebel spaceships, striking from a hidden base, have won their first victory against the evil Galactic Empire. ";
break;
case 2:
demo.innerHTML = "During the battle, Rebel spies managed to steal secret plans to the Empire's ultimate weapon, the Death Star, an armored space station with enough power to destroy an entire planet.";
break;
case 3:
demo.innerHTML = "Pursued by the Empire's sinister agents, Princess Leia races home aboard her starship, custodian of the stolen plans that can save her people and restore freedom to the galaxy....";
break;
case 0:
demo.innerHTML = "A long time ago, in a galaxy far, far away..";
break;
}
}
</script>
</head>
<body>
<div id="demo">
A long time ago, in a galaxy far, far away..
</div>
<ul>
<li><span id ="s1">Part 1</span></li>
<li><span id="s2">Part 2</span></li>
<li><span id="s3">Part 3</span></li>
<li><span id="s4">Reset</span></li>
</ul>
</body>
</html>
答案 0 :(得分:5)
当你做这样的事情时:
document.getElementById("s1").onclick = print(1);
document.getElementById("s2").onclick = print(2);
document.getElementById("s3").onclick = print(3);
document.getElementById("s4").onclick = print(0);
您实际上是使用给定参数调用print()
函数,然后将该函数的结果(实际上是undefined
)绑定到onclick事件。我想你想做的是这样的事情:
document.getElementById("s1").onclick = function(){ print(1) };
document.getElementById("s2").onclick = function(){ print(2) };
document.getElementById("s3").onclick = function(){ print(3) };
document.getElementById("s4").onclick = function(){ print(0) };
这将附加一个调用print()
函数的函数。