我正在尝试让这段代码正常工作,但我一生都无法理解为什么它不起作用。我已经尝试过 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>
最佳答案
当你做这样的事情时:
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()
函数,然后将该函数的结果(实际上是未定义
)绑定(bind)到 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()
函数的函数。
关于javascript - 你能帮我解决问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15308418/