本文介绍了如何使用addEventListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作一个脚本,每次按下一个按钮时创建div元素。最初我有一个函数调用inline onclick 属性,但jslint不喜欢这样,所以我把它移出,而尝试使用 addEventListener click,function());



我从来没有使用过 addEventListener c>

问题是它创建了一个 div


$ b

这里是我有:

 < body& 
< form>
< textarea id =a>< / textarea>
< br>
< input value =buttontype =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>
解决方案>

按如下所示更改事件侦听器

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

,你传递的结果 createEntry 作为事件监听器,而不是函数本身



更多信息:



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


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

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

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

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>
解决方案

Change the event listener like this

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

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

More information here:

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

这篇关于如何使用addEventListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 17:35