为什么这段代码输出不出任何东西?

时间:2014-05-19 16:46:07

标签: javascript

<!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的新手。这是我写的代码。我发现这段代码没有任何问题。有人可以帮忙吗?谢谢。问题是当我点击按钮时,没有任何反应。

1 个答案:

答案 0 :(得分:7)

  

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

因为您的函数名称与select对象的window方法冲突,因为全局函数被抛到window上。如果您将功能名称更改为其他名称(例如foo),则可以使用"test"(至少)替换您的页面。

Here's a live copy您的代码无效,here's a copy函数名称已更改为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不再是全局的,因此不再发生冲突。


仅仅为了它的价值,here's a version没有使用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>