【问题标题】:Adding a listener to a button created by .innerHTML将侦听器添加到由 .innerHTML 创建的按钮
【发布时间】:2019-07-03 16:44:47
【问题描述】:

我正在尝试在接收到侦听器后将侦听器添加到由 .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 变量创建的带有“删除按钮”类的按钮可以点击并发送一个 console.log

【问题讨论】:

  • 您的问题是什么,您尝试过什么?花几分钟阅读How to Ask

标签: javascript event-handling html-lists innerhtml addeventlistener


【解决方案1】:

不清楚您想在控制台中输出什么,但简单的方法是将 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);
}

【讨论】:

    猜你喜欢
    • 2012-11-26
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 2014-07-07
    相关资源
    最近更新 更多