2

我试图让这段代码工作,但我一生都无法理解为什么它不会。我已经尝试过 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>
4

1 回答 1

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()函数。

于 2013-03-09T07:40:50.483 回答