javascript - Adding Event Listener to dynamically created divs - Stack Overflow

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

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',gotoOutesLO, false);

The Function that is called by the click event:

function gotoOutesLO(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!

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',gotoOutesLO, false);

The Function that is called by the click event:

function gotoOutesLO(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!

Share Improve this question edited Sep 7, 2020 at 7:23 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked May 27, 2014 at 5:41 user2051921user2051921 251 silver badge5 bronze badges 1
  • 2 remove = in listDiv.addEventListener = ('click',gotoOutesLO, false); – user2587132 Commented May 27, 2014 at 5:44
Add a ment  | 

3 Answers 3

Reset to default 6

Change

listDiv.addEventListener = ('click',gotoOutesLO, false);

to

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

addEventListener is a function remove equal:

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

function gotoOutesLO(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...

Here is javascript click event

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742352171a4427737.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信