Javascript addEventListener()不工作
好的,我试着用addEventListener函数制作这个页面,来解决点击按钮的问题;它不起作用。我缩小了范围,删除了除侦听器所需的基本元素以外的所有内容,剩下的内容如下:Javascript addEventListener()不工作,javascript,addeventlistener,Javascript,Addeventlistener,好的,我试着用addEventListener函数制作这个页面,来解决点击按钮的问题;它不起作用。我缩小了范围,删除了除侦听器所需的基本元素以外的所有内容,剩下的内容如下: <!DOCTYPE html> <html> <head> <script type="text/javascript"> function init(){ document.getElementById("test").addEventListener("moused
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function init(){
document.getElementById("test").addEventListener("mousedown", function(){
alert("Test successful");
});
}
body.onload = init();
</script>
</head>
<body>
<button id="test">Click</button>
</body>
</html>
函数init(){
document.getElementById(“test”).addEventListener(“mousedown”,function()){
警报(“测试成功”);
});
}
body.onload=init();
点击
这也不起作用,所以我知道问题出在我上面的语法中。请注意,当我拿走body.onload=init()时
并将onload=“init()”
放入body标记中,它确实起了作用:问题是,我不想让它内联。有什么建议吗
注意:请记住,这个问题是而不是关于JS中如何存在bug的问题,即使标题可能暗示存在bug,也是关于我如何无法使它工作,因为我可能是语法错误。如果愿意,请随意重命名它。首先,您应该通过
document.body
访问body元素。但是,onload
是在窗口中定义的,因此您实际上需要:
window.onload = init();
但是,这将执行init()
方法,并将返回值存储在window.onload
中。显然,这不是您想要的:您希望init
函数充当onload
处理程序。因此,你应该写:
window.onload = init;
尽管我也建议使用addEventListener
:
window.addEventListener("load", init);
这是因为未定义body
,正确的是document.body。
此外,可能document.body尚未定义,因为head
标记在body
标记之前呈现,因此最好检查窗口或文档的加载时间。
请尝试以下代码:
function init(){
document.getElementById("test").addEventListener("mousedown", function(){
alert("Test successful");
});
}
document.addEventListener('load',init);//Or also, window.addEventListener
body.onload=init()
不是指主体的方式,而是使用窗口-
不要在那里调用方法,引用它(不带括号)
window.onload=init强>
通过第三个参数,即使它是错误的-
function init(){
document.getElementById("test").addEventListener("mousedown", function(){
alert("Test successful");
},false);
}
请注意,9版之前的IE不支持addEventListener。第三种解决方案是目前为止最好的:)谢谢。