Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

javascript - How to use 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>

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...