Adding Event Listener to dynamically created divs

让人想犯罪 __ 提交于 2019-12-24 00:59:36

问题


I am trying to add click event listener to my divs that I am creating in my JS dynamically.

My Javascript snippet of function that is called each time to create the Div:

var listDiv = document.createElement("div");
listDiv.className = "list";
listDiv.addEventListener = ('click',gotoOutcomesLO, false);

The Function that is called by the click event:

function gotoOutcomesLO(e){
if(typeof(Storage)!=="undefined"){
        var ele = e.target;
        var text = ele.getAttribute("name");
        sessionStorage.test = text;
}
}

I don't see any click events added to my HTML and not sure what's wrong. Any pointers would be helpful! Thanks!


回答1:


Change - listDiv.addEventListener = ('click',gotoOutcomesLO, false);

to

listDiv.addEventListener('click',gotoOutcomesLO, false);




回答2:


addEventListener is a function remove equal:

var listDiv = document.createElement("div");
listDiv.className = "list";
listDiv.addEventListener('click', gotoOutcomesLO, false);

function gotoOutcomesLO(e) {
    if(typeof(Storage)!=="undefined") {
        var ele = e.target;
        var text = ele.getAttribute("name");
        sessionStorage.test = text;
    }
}

Also I guess you append listDiv to a node...




回答3:


Here is javascript click event

var listDiv = document.createElement("div");
listDiv.className = "list";
listDiv.onclick = function(){
   alert('onclick fired')
}


来源:https://stackoverflow.com/questions/23881804/adding-event-listener-to-dynamically-created-divs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!