Как добавить EventListener в html-элемент, если элемент перемещается в html через этот файл js?

0

Вопрос

Я нажал на <form> в HTML-файл с помощью файла JS, а затем добавьте в эту форму элемент списка событий, но получается ошибка: Неперехваченная ошибка типа: Не удается прочитать свойства null (чтение "addEventListener").

Я предполагаю, что это связано с тем, что этот файл JS напрямую связан с файлом HTML, что означает, что JS может быть загружен до <form>.

Кто-нибудь может, пожалуйста, сказать мне, как это решить?

Коды JS приведены ниже:

// skip to the input fields
$start.addEventListener('click', function(){
    $chooseStory.remove()

    const inputs = []
    
    inputs.push(`
        <form id="form">
        <label>Provide The Following Words</lable>
    `)

    // assign words of stories to names and placeholders of inputs
    // the input will automatically loop for as many as the words are
    for (const word of stories[$index.value].words) {
    inputs.push(`
      <input type="text" name='${word}' placeholder="${word}">
    `)}

    inputs.push(`
        <button type="submit" id="submit"> Read Story </button>
        <code id="result"></code>
        </form>
    `)

    const inputsField = inputs.join('')
    $container.innerHTML += inputsField
})

// retrieve value of the form

const $form = document.getElementById('form')

$form.addEventListener('submit', function(e){
  e.preventDefault()
})
addeventlistener javascript typeerror
2021-11-20 22:21:07
1

Лучший ответ

1

Вам необходимо использовать делегирование событий, в котором прослушиватель прикреплен к родительскому компоненту, который захватывает события из дочерних элементов, когда они "всплывают" в DOM.

// Adds a new form to the page
function addForm() {

  const html = `
    <form id="form">
      <label>Provide The Following Words</lable>
      <input />
      <button type="submit" id="submit">Read Story</button>
      <code id="result"></code>
    </form>
    `;

  // Add the new HTML to the container
  container.insertAdjacentHTML('beforeend', html);

}

function handleClick(e) {

  // In this example we just want to
  // to log the input value to the console
  // so we first prevent the form from submitting
  e.preventDefault();

  // Get the id of the submitted form and
  // use that to get the input element
  // Then we log the input value
  const { id } = e.target;
  const input = document.querySelector(`#${id} input`);
  console.log(input.value);

}

// Cache the container, and add the listener to it
const container = document.querySelector('#container');
container.addEventListener('submit', handleClick, false);

// Add the form to the DOM
addForm();
<div id="container"></div>

2021-11-20 22:52:06

Привет, Энди! Спасибо, что помогли мне, делегирование мероприятий действительно работает!!
rubyhui520

НП Энди! Извините за поздний ответ, я новичок на этом сайте, поэтому я не знаком со всеми функциями
rubyhui520

На других языках

Эта страница на других языках

Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................