我正在构建一个Web应用程序,该应用程序根据输入到表单的内容在队列中创建元素。这些元素的HTML是由“模板”生成的,其中包含几个图标,一旦我可以添加addEventHandler调用,这些图标将用作按钮,但由于我的一生,我无法使其正常工作。应该在DOM加载后调用我的事件处理程序,所以我不确定是什么问题。
这是我的(基本)代码:
// 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();
});
答案 0 :(得分:0)
完成container.innerHTML = 'html string'
后,您可以使用
container.querySelector('.someIconClass').addEventListener(eventName, handler)