Динамические добавления слушателей
Недавно столкнулся с таким вопросом про добавление динамических слушателей: при нажатии на определённый таргет я меняю содержимое формы через innerHTML, а затем добавляю на все поля (input) слушатели через цикл. Вопрос заключается в следующем: такая практика добавления слушателей является хорошей или плохой? И как лучше добавлять слушатели к динамическим элементам?
Если нужны примеры листингов: HTML:
<div class="select__field" id="select__user">
<input class="select__radio" type="radio" name="select__radio" id="select-radio-seeker" value="seeker">
<label for="select-radio-seeker" class="__label" id="label-radio-seeker">Соискатель</label>
<input class="select__radio" type="radio" name="select__radio" id="select-radio-employer" value="employer">
<label for="select-radio-employer" class="__label" id="label-radio-employer">Работодатель</label>
</div>
<div class="form__body empty" id="form-body"></div>
JS:
const createFormBodyInner = (type, formBody) => {
formBody.classList.remove('empty');
if (type === 'seeker') {
formBody.innerHTML = `
<div class="input__field" id="login-field">
<input type="text" name="user-login" class="__input modern" id="login-input" placeholder="Введите логин" autocomplete="off">
</div>
// Далее ещё создаются поля
`;
} else if (type === 'employer') {
formBody.innerHTML = `
<div class="input__field" id="login-field">
<input type="text" name="user-login" class="__input modern" id="login-input" placeholder="Введите логин" autocomplete="off">
</div>
// Далее ещё создаются поля
`;
}
return;
}
selectUser.addEventListener('click', (event) => {
const target = event.target,
seeker = document.getElementById('label-radio-seeker'),
employer = document.getElementById('label-radio-employer'),
seekerInput = document.getElementById('select-radio-seeker'),
employerInput = document.getElementById('select-radio-employer'),
formBody = document.getElementById('form-body');
if (target === seeker && !seekerInput.checked) {
createFormBodyInner('seeker', formBody);
const selected = document.querySelectorAll('.__input');
for (let i = 0; i < selected.length; i++) {
selected[i].addEventListener('input', () => {
// Здесь другие функции
})
}
} else if (target === employer && !employerInput.checked) {
createFormBodyInner('employer', formBody);
const selected = document.querySelectorAll('.__input');
}
})