简体   繁体   中英

adding click event in newly created div in javascript

I am creating a new div on a click of button and inside that onclick function I am adding a click event to newly created div but its not working.

document.getElementById('blah').onclick = function(){
    var innerDiv = document.createElement("div");
    document.getElementById('container').appendChild(innerDiv);
innerDiv.onclick =createWorkFunction;
}
function createWorkFunction(e){
 alert();
}

can anybody quickly help me

Your code is corrct, But you did not set the text of the your div (an empty div can not be clicked by an user), Try this:

document.getElementById('blah').onclick = function(){
    var innerDiv = document.createElement("div");
    innerDiv.innerHTML = 'This is a div'; // set it's text
    document.getElementById('container').appendChild(innerDiv);
    innerDiv.onclick = createWorkFunction;
}
function createWorkFunction(e){
    alert('this is some text');
}

Also it's better to use addEventListener

(function() {
    var oBlah = document.getElementById('blah');
    oBlah.addEventListener('click', function() {
        var innerDiv = document.createElement("div");
        document.getElementById('container').appendChild(innerDiv);
    }, false);
    innerDiv.addEventListener('click', function() {
        alert();
    }, false);
})();

This should help.

try this:

innerDiv.setAttribute("onclick","createWorkFunction()")   

function createWorkFunction(){
 alert("working");
}

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