简体   繁体   中英

Add event handler to element ID created within .innerHTML

I have a web app I'm building that creates elements in a queue based on what was input into a form. The HTML for these elements are generated by a "template" that has a couple icons in it that will be used as buttons once I can add my addEventHandler call, but for the life of me I can't get it to work. My eventhandler should be called after the DOM has loaded, so I'm not sure what the issue is.

Here's my (basic) code:

 // Init app let init = function() { // Set up user input handling submit.addEventListener('click', inputHandler); // TODO: Fix button contentInput.addEventListener('keypress', function(e) { if (e.keyCode == 13 && contentInput.value != '') { e.preventDefault(); inputHandler(); } }); let getFlag = document.getElementById('flag--LRI3LcUxQ9W5RfIWoc8'); getFlag.addEventListener('click', function() { console.log('IT WORKED'); }); } let renderQueryList = function() { // Determine which item to render (timestamp, number of views, flagged) const oneDay = 60 * 60 * 24 * 1000; const arrLength = queue.length; queueDisplay.innerHTML = ''; for (i = 0; i < arrLength; i++) { let element = queue[i]; let whenAdded = element.age; if (!element.hasOwnProperty('type')) { element.type = 'text'; } if ((now - whenAdded) > oneDay) { // console.log(element.text + ': this element is expired') return element.expired === true; } // TODO: check for type in templates, fallback to default type or display next item let singleElement = contentTypeTemplates[element.type](element); // for each item in list queueDisplay.appendChild(singleElement); } } // Set up templates let contentTypeTemplates = { text: function(contentItem, index) { let container = document.createElement('div'); container.className = 'queueItem'; container.setAttribute('id', contentItem.key); container.innerHTML = contentItem.text + '<div class="queueControls">' + '<i style="display: none;" class=" delete fas fa-times-circle" id="delete-' + contentItem.key + '"></i>' + '<i class="flag fas fa-flag" id="flag-' + contentItem.key + '"></i>' + '<i class="permanent fas fa-thumbtack" id="permanent-' + contentItem.key + '"></i>' + '</div>'; return container; }, image: function(contentItem) { } } document.addEventListener("DOMContentLoaded", function(event) { init(); }); 

完成container.innerHTML = 'html string'您可以使用

container.querySelector('.someIconClass').addEventListener(eventName, handler)

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