在动态创建的按钮上单击事件侦听器

问题描述

在使用.onclick一组动态创建的按钮时,我遇到了一些真正的困难。昨天我在一个正在进行的实际项目中遇到了同样的问题,因此决定尝试这个我拥有的实践项目,并且问题仍然存在,所以这绝对是我的问题。

起初我以为可能与我创建按钮的方式有关。所以这就是我一开始创建它的方式,就像这样:

function userData() {
    fetch("https://jsonplaceholder.typicode.com/users")
    .then(response => response.json())
    .then(users => {
        let output = '<h6>List of Users</h6>';
        output += '<div class="list-group">';
        users.forEach(function(user) {
            output += `
                <button data-user="${user.id} type="button" class="list-group-item list-group-item-action">
                    <strong>${user.name}</strong><br>
                    ${user.email}<br>
                    ${user.address.city}<br>
                </button>
            `;
        });
        output += '</div>';
        document.querySelector('#response').innerHTML = output;
        });
}

我认为这可能不是解决问题的最佳方法,所以我决定改用document.createElement方法,现在看起来就像这样:

document.addEventListener('DOMContentLoaded',function() {
userData();
document.querySelectorAll('button').forEach(button => {
    button.onclick = function(){
        userSelect(this.dataset.user_id);
    }
})

});


function userData() {
    fetch("https://jsonplaceholder.typicode.com/users")
    .then(response => response.json())
    .then(users => {
        const h6 = document.createElement("h6");
        h6.innerText = "List of Users";
        const userList = document.createElement("div");
        userList.className = "list-group";
        users.forEach(function(user) {
            const userButton = document.createElement("button");
            userButton.className = "list-group-item list-group-item-action";
            userButton.setAttribute('data-user',`${user.id}`);
            userButton.innerHTML = `
            <strong>${user.name}</strong><br>
            ${user.email}<br>
            ${user.address.city}<br>
            `;
            userList.appendChild(userButton);
        });
        const container = document.querySelector('#response');
        container.appendChild(h6);
        container.insertBefore(userList,h6.nextSibling);
    });
}


function userSelect(user_id) {
    fetch(`https://jsonplaceholder.typicode.com/users/${user_id}`)
    .then(response => response.json())
    .then(user => {
        console.log(user);
    });
}

问题是,当我单击按钮时,控制台上什么都没有显示,但是当我直接使用函数userSelect(6);时,该用户对象显示正常。 .onclick确实在某处出错,但是我真的不知道出什么问题了。如果我能在这里解决问题,我知道我将能够解决我正在从事的项目的问题。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)