click event on innerHTML generated div

时光毁灭记忆、已成空白 提交于 2019-12-24 16:53:33

问题


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/



来源:https://stackoverflow.com/questions/31876652/click-event-on-innerhtml-generated-div

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