简体   繁体   中英

EventListener work only once

I have this HTML code,

<input type='button' id='addQuestion' class='btn' value='Add Question'/>

and a JavaScript Code,

var question;
document.addEventListener('DOMContentLoaded', function(){
    var aQ = document.getElementById("addQuestion");
    aQ.addEventListener("click",addQ);
});

function addQ(){
question = question + 1;
document.getElementById("content").innerHTML += "<div>question</div>";
}

It supposed to be able to create more than one div. I tried to use onclick instead of EventListener,

<input type='button' id='addQuestion' class='btn' onclick="addQ()" value='Add Question'/>

and it is working.

Some minor changes ( demo ):

    var question = 0; // init as typeof Number 

    window.addEventListener('DOMContentLoaded', function(){
        var aQ = document.getElementById("addQuestion");
        aQ.addEventListener("click",addQ);
    });

    function addQ(){
        question = question + 1;
        document.getElementById("content").innerHTML += "<div>"+question+"</div>"; 
        //                                    Use the variable--^^^^^^^^
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM