我正在尝试在收到侦听器后将侦听器添加到 .innerHTML 创建的按钮中。这是代码:
let inputConfirm = document.getElementById('inputConfirm');
let inputText = document.getElementById('inputText');
let displayList = document.getElementById('displayList');
inputConfirm.addEventListener('click', e=>listElement())
const listElement = () => {
let inputValue = inputText.value //takes input from textbox
let newValue = "<li class='each-item'><div class='listbox'>" + inputValue + "<input type='checkbox' class='checkbox'><button class='delete-button'>X</button></div></li>"; //EACH list element that I want to add to the ordered list.
if(inputValue !== ""){
displayList.innerHTML += newValue;
inputText.value = "";//clears the text box
};
};
我需要通过 newValue 变量创建的带有类"删除按钮"的按钮是可点击的并发送控制台.log
目前还不清楚您想在控制台中输出什么,但简单的方法是将 onclick 事件添加到 .innerHTML 中并添加一个函数。
let inputConfirm = document.getElementById('inputConfirm');
let inputText = document.getElementById('inputText');
let displayList = document.getElementById('displayList');
inputConfirm.addEventListener('click', e=>listElement())
const listElement = () => {
let inputValue = inputText.value //takes input from textbox
let newValue = "<li class='each-item'><div class='listbox'>" + inputValue + "<input type='checkbox' class='checkbox'><button class='delete-button' onclick='toConsole(event)'>X</button></div></li>"; //EACH list element that I want to add to the ordered list.
if(inputValue !== ""){
displayList.innerHTML += newValue;
inputText.value = "";//clears the text box
};
};
function toConsole(e){
console.log(e.target);
}