click event on innerHTML generated div

2019-08-09 23:17发布

问题:

I have a 'div' element generated in javascript with 'innerHTML' property.

(...).innerHTML = 'sometext'+'<div id=\"a\">word</div>'+obj.something+'othertext';

Anyway onclick event is not working.

document.getElementById('a').onclick = function() {
    //do something
}

What is the problem? How do I resolve it (pure javascript, no libraries)?

回答1:

You could delegate the event listening to the parent to which you are innerHTML-ing the div , in yout code indicated by (...). This would handle the events fired in the (...) and you can perform actions conditioned to event.target.id === 'a'

(...).onclick = function(event) {
    if (event.target.id === 'a') {
    //Do your stuff
    }
}

This way you not need to worry about if, when you attach the listener, you have already created the div dinamically or not. Also, to register the event handler, I suggest proper event handle registering (https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)



回答2:

You need to bind that id with the function after you added the the innerhtml to the outer html

function bindingFunction(){
    document.getElementById('a').onclick = function() {
//     Your code
    }
}

Just after adding the innerHTML

(...).innerHTML = 'sometext'+'<div id=\"a\">word</div>'+obj.something+'othertext';
bindingFunction();

This will work.



回答3:

Please call this function :

document.getElementById('a').onclick = function() {
    //do something
}

Just after the

(...).innerHTML = 'sometext'+'<div id=\"a\">word</div>'+obj.something+'othertext';


回答4:

Working Example:

Javascript Code

document.getElementById('resultDiv').innerHTML = '<div id=\"a\">Test onclick</div>';

document.getElementById('a').onclick = function() {
    alert("Click Event Fired !")
}

Demo for you: https://jsfiddle.net/be3a90gw/4/