<!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>
Run Code Online (Sandbox Code Playgroud)
我是javascript的新手.这是我写的代码.我发现这段代码没有任何问题.有人可以帮忙吗?谢谢.问题是当我点击按钮时,没有任何反应.
为什么这段代码输出不出任何东西?
因为您的函数名称与对象的select方法冲突window,因为全局函数被抛出window.如果您将函数名称更改为其他名称(foo例如),那么您的页面将替换为单词"test"(至少).
这是你的代码的实时副本,它不起作用,这里是一个功能名称改为的副本foo,这样做.
这是避免使用全局变量的众多原因之一.在这种情况下,例如,你可以给你的按钮一个id(id="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/>");
}
}
})();
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为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>
Run Code Online (Sandbox Code Playgroud)