我遇到addEventListener问题。当我点击第三个div标签时,它不会改变背景颜色,警报也不起作用。
这是我的html结构:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="myscript.js"></script>
</head>
<body>
<p>Click the button to display an alert box:</p>
<div>Robert</div>
<div>Arthur</div>
<div>Procedure(Third)</div>
<div>Fourth</div>
<button onclick="myfunc()">Try it</button>
</body>
这是javascript文件:
var Ar = ["red", "yellow", "green", "blue"]
function getRandomInt(min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function myfunc() {
alert(getRandomInt(0,5));
}
function Group(handler) {
var R = [];
for (var I = 0, E = document.getElementsByTagName('div'), L = E.length; I < L; I++) {
handler && handler.call(E[I]);
if (!handler)
R.push(E[I]);
}
return R;
}
//get third div tags and set a handler
Group()[2].addEventListener("click", handler, false);
function handler() {
alert("Test!");
Group()[2].style.backgroundColor = Ar[getRandomInt(0,3)];
}
答案 0 :(得分:3)
您正在尝试在加载元素之前访问这些元素。
在页面末尾包含您的脚本,它将起作用。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Click the button to display an alert box:</p>
<div>Robert</div>
<div>Arthur</div>
<div>Procedure(Third)</div>
<div>Fourth</div>
<button onclick="myfunc()">Try it</button>
</body>
<script type="text/javascript" src="myscript.js"></script>
答案 1 :(得分:3)
像这样修改你的代码。
<body>
<p>Click the button to display an alert box:</p>
<div>Robert</div>
<div>Arthur</div>
<div>Procedure(Third)</div>
<div>Fourth</div>
<button onclick="myfunc()">Try it</button>
<script type="text/javascript">
Group()[2].addEventListener("click", handler, false);
</script>
</body>