简体   繁体   中英

How to add an onclick function to dynamically created divs with pure Javascript

I currently am dynamically creating divs based on a XML file in one function, using the code below.

var ftdImg = "<div class='single-img' id='" + pid + "'><a href='#'><img src='" + projHomeThumbURL + "'/></a><p>" + titleEdit(projName) + "</p><p>" + titleEdit(projCat) + "</p><p>" + projDate + "</p></div>";
var divTag = document.createElement("div");

function createNew(standIn) {
    divTag.innerHTML = standIn;
    document.getElementById("container").appendChild(divTag);
}

Currently, this code works. I want to add an on click function that replaces the innerHtml of "standin", which is the var ftdImg in my case, with projImgTag:

var projImgTag = "<div class ='project-image "+projName+"' id='"+pid+"'><a href='"+projFull+"'><img src='"+projThumb+"/></a></div>";

The vanilla js DOM event for handling clicks is onclick() :

MDN's docs for .onclick()

var divTag = document.createElement("div");
divTag.onclick = function() {
    /* ... */
};

EDIT

As well noted by torazaburo , the documentation adds:

You may be inclined to use the EventTarget.addEventListener() method instead, since it is more flexible and part of the DOM Events specification.

Example:

var divTag = document.createElement("div");
divTag.addEventListener("click", function() {
    /* ... */
}, false);

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