addEventListener()不起作用 [英] addEventListener() not working
问题描述
好,所以我尝试使用addEventListener函数制作此页面,以解决按钮的单击问题;没用我通过删除除侦听器所需的基本元素以外的所有内容来缩小范围,然后剩下以下内容:
Ok, so I tried to make this page with an addEventListener function, to address the clicking of a button; It didn't work. I narrowed it down by deleting everything but the basic elements needed for the listener, and am left with the following:
<!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>
也不起作用,所以我知道问题出在我上面的语法中。请注意,当我拿走 body.onload = init();
并放下 onload = init()
进入body标签,它确实起作用了:O问题是,我不想将其内联。有什么建议么?
which didn't work either, so I know the issue is in my syntax of the above. Mind you, when I took away body.onload = init();
and instead put onload="init()"
into the body tag, it did work :O Problem is, I don't want to have it inline. Any suggestions?
注意:请记住,关于JS中是否存在bug的问题不是,即使标题可能如此,这是因为我可能语法错误,因此我无法使其正常工作。
Note: Do bear in mind that this question is not about how there is a bug in JS, even if the title may suggest so, it is about how I can't get it to work since I've probably got the syntax wrong. Please feel free to rename it if you wish.
推荐答案
首先,您应该通过<$ c $访问body元素。 c> document.body 。但是, onload
是在窗口
上定义的,因此您实际上需要:
First of all, you should access the body element through document.body
. However, onload
is defined on window
, so you actually need:
window.onload = init();
但是,这将执行 init()
方法,并将返回值存储在 window.onload
中。显然,这不是您想要的:您希望 init
函数充当 onload
处理程序。因此,您应该这样写:
However, that would execute the init()
method and store the return value in window.onload
. Obviously, that's not what you want: you want the init
function to act as onload
handler. Therefore, you should have written:
window.onload = init;
尽管我建议使用 addEventListener
以及:
window.addEventListener("load", init);
这篇关于addEventListener()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!