简体   繁体   中英

click event on innerHTML generated div

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)?

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 )

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.

Please call this function :

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

Just after the

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

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/

Javascript - no libraries

 var div = document.getElementById('1'); div.onclick = function(event) { if(div.innerHTML == 'Click here'){ div.innerHTML = '<b>I like this!</b>'; }else{ div.innerHTML = 'Click here'; } }
 <div id="1">Click here</div>

jQuery

 var div = $('#1') div.on('click',function(event){ if(div.html() == 'Click me'){ div.html('<b>I like this</b>'); }else{ div.html('Click me'); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="1">Click me</div>

You can use the onclick event directly in the innerHTML string, and I suggest you use template literals instead of single quotes

(...).innerHTML = `sometext <div id="a" onclick="someFunction('${data}')">word</div> ${obj.something} ${othertext}`;

You can pass dynamic or static data into the function. The example above passes dynamic data where data represents a variable. To pass static data just do so without the ${} eg

someFunction('data');
 <button onClick="
                document.querySelector('.tab.active').classList.remove('active'); 
                document.getElementById('${before}').classList.add('active')
            " class="ghost">
                <svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M20 11.1111H7.83L13.42 5.52108L12 4.11108L4 12.1111L12 20.1111L13.41 18.7011L7.83 13.1111H20V11.1111Z" fill="white"/>
                </svg>
            </button>

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