javascript 如何使用 addEventListener

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13771025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:44:05  来源:igfitidea点击:

How to use addEventListener

javascriptclickaddeventlistener

提问by Kyle Messner

I was making a script that creates div elements each time a button is pressed. Originally I had the function called inline with the onclickattribute, but jslint doesn't like that so I moved it out and instead tried to use addEventListener("click",function());

我正在制作一个脚本,每次按下按钮时都会创建 div 元素。最初我有一个与onclick属性内联调用的函数,但 jslint 不喜欢那样,所以我将它移出并尝试使用addEventListener("click",function());

I've never used addEventListener()before so I'm not even sure I am using it correctly.

我以前从未使用addEventListener()过,所以我什至不确定我是否正确使用它。

The problem is that it creates one divwhen the page loads and won't do anything when the button is pressed.

问题是它div在页面加载时创建一个,而在按下按钮时不会做任何事情。

Thank you in advance.

先感谢您。

here is what I have:

这是我所拥有的:

<body>
<form>
    <textarea id="a"></textarea>    
    <br>
    <input value="button" type="button">
</form>
<div id="content">
</div>
<script>
    /*jslint browser:true */
    function createEntry(text) {
        "use strict";

        var div = document.createElement("div");
        div.setAttribute("class", "test");
        document.getElementById("content").appendChild(div);
    }
    var input = document.getElementsByTagName("input")[0];
    input.addEventListener("click", createEntry(document.getElementById('a').value));
</script>

回答by lostsource

Change the event listener like this

像这样更改事件侦听器

input.addEventListener("click", function(){
    createEntry(document.getElementById('a').value);
});

as it stands, you're passing the result of createEntryas an event listener, not the function itself

就目前而言,您将结果createEntry作为事件侦听器传递,而不是函数本身

More information here:

更多信息在这里:

https://developer.mozilla.org/en/docs/DOM/element.addEventListener

https://developer.mozilla.org/en/docs/DOM/element.addEventListener

回答by Chiel ten Brinke

Change this line

改变这一行

input.addEventListener("click", createEntry(document.getElementById('a').value));

into

进入

input.addEventListener("click", function(){
createEntry(document.getElementById('a').value);
});

回答by Rakesh Menon

Try using a JavaScript library like jQuery for event handling and DOM manipulation, to be browser safe and for uniformity.

尝试使用像 jQuery 这样的 JavaScript 库进行事件处理和 DOM 操作,以确保浏览器安全和统一。

You can use the event handlers in jQuery like the following:

您可以使用 jQuery 中的事件处理程序,如下所示:

$(<element_selector>).on("click", function (event) {
     // your code here...
});