繁体   English   中英

为什么这段代码不输出任何内容?

[英]Why doesn't this piece of code output anything?

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>

    <script language="javascript" type="text/javascript" >
        var per1 = { name: "john", age: 23 }; 
        var per2 = { name: "Robin", age: 10 };
        var per3 = { name: "temp", age: 15 };

        var people = new Array(3);
        people[0] = per1;
        people[1] = per2;
        people[2] = per3;

        function select()
        {
            document.write("test");
            for(var i=0; i<people.length; i++)
            {
                if (people[i].age < 20)
                    document.write(people[i].name + "<br/>");
            }

        }

    </script>

    <header id="temp">temp</header>
    <input type="button" value="touch me" onclick="select()" />

</body>
</html>

我对javascript完全陌生。 这是我写的代码。 我找不到这段代码有什么问题。 有人可以帮忙吗? 谢谢。 问题是当我单击按钮时,什么也没发生。

为什么这段代码不输出任何内容?

由于您的函数名称与window对象的select方法冲突,因为全局函数被抛出到window 如果您将函数名称更改为其他名称(例如foo ),它将起作用,因为您将页面替换为单词"test" (至少)。

是您的代码的实时副本 ,该副本不起作用, 这是一个将函数名称更改为foo 的副本

这是避免使用全局变量的众多原因之一。 例如,在这种情况下,您可以为您的按钮指定一个idid="theButton" )而不提供onclick ,然后使用此经过最小修改的脚本:

(function() {
  var per1 = { name: "john", age: 23 }; 
  var per2 = { name: "Robin", age: 10 };
  var per3 = { name: "temp", age: 15 };

  var people = new Array(3);
  people[0] = per1;
  people[1] = per2;
  people[2] = per3;

  document.getElementById("theButton").onclick = select;

  function select()
  {
      document.write("test");
      for(var i=0; i<people.length; i++)
      {
          if (people[i].age < 20)
              document.write(people[i].name + "<br/>");
      }
  }
})();

之所以select是因为select不再是全局的,因此不再发生冲突。


仅仅为了它的价值, 这是一个不使用document.write 的版本 (最好避免使用),使用代码连接处理程序,并使用数组文字符号:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <header id="temp">temp</header>
    <input type="button" value="touch me" id="theButton" />
    <!-- Note that the script is *below* the content it uses -->
    <script language="javascript" type="text/javascript" >
    (function(){
        var people = [
            { name: "john", age: 23 },
            { name: "Robin", age: 10 },
            { name: "temp", age: 15 }
        ];

        document.getElementById("theButton").onclick = run;

        function run()
        {
            display("test");
            for(var i=0; i<people.length; i++)
            {
                if (people[i].age < 20)
                {
                    display(people[i].name);
                }
            }
        }

        function display(msg) {
            var p = document.createElement('p');
            p.innerHTML = String(msg);
            document.body.appendChild(p);
        }
    })();
    </script>
</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM