0

当我们在输入中按下键输入时,我会创建标签,并且我想选中复选框并应用事件更改。那么如何选择 createElement 创建的标签呢?

HTML

<div class="container">
        <div class="row">
            <div class="col-4">
                <div class="container-list">
                    <h1>To Do List</h1>
                    <input type="text" placeholder="Ajouter une tache">

                </div>
            </div>
        </div>

    </div>

JS

const list = document.querySelector('.container-list');
const input = document.querySelector('input');
// const icons = document.querySelectorAll('i');
const listIcons = document.querySelectorAll('.list input[type=checkbox]');

input.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
        const listAdded = document.createElement('div');
        listAdded.innerHTML = "<input type='checkbox'>" + '<span id="listContent">' + input.value + '</span>' + '<i class="fas fa-edit"></i>' + '<i class="fas fa-trash"></i>';
        listAdded.setAttribute('class', 'list');
        list.appendChild(listAdded);
    };
});

console.log(listIcons)

listIcons.forEach(listIcon => {
    listIcon.addEventListener('change', () => {
        alert('test')
    });
});
4

2 回答 2

0

That's because you're defining listIcons once at the top of your file and not updating it after you create new elements. so my suggestion is to add the event listener for each element after you create it in the keydown event listener.

于 2020-06-16T19:03:02.303 回答
0

当您调用document.createElement. 如果您希望在其他函数中或在创建元素的函数范围之外使用该元素,只需将该变量声明为全局变量。

在您提供的代码中,该listAdded变量正是您要查找的。

于 2020-06-16T18:57:01.037 回答