Jak dodać EventListener w html-element, jeśli element jest przesuwany w html poprzez ten plik js?

0

Pytanie

Kliknąłem na <form> w pliku HTML za pomocą pliku JS, a następnie dodać do formularza element listy zdarzeń, ale okazuje się błąd: Неперехваченная błąd typu: Nie można odczytać właściwości null (czytanie "addEventListener").

Myślę, że jest to związane z tym, że ten plik JS jest bezpośrednio powiązany z plikiem HTML, co oznacza, że JS może być załadowany do <form>.

Czy ktoś może, proszę mi powiedzieć, jak to rozwiązać?

Kody JS przedstawiono poniżej:

// 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

Najlepsza odpowiedź

1

Musisz użyć delegowanie zdarzeń, w którym detektor jest przymocowany do nadrzędnego składnika, który przechwytuje zdarzenia z podrzędnych elementów, gdy są "pojawiają się" w 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

Cześć, Andy! Dziękuję, że pomogłeś mi, delegowanie działań naprawdę działa!!
rubyhui520

TM Andy! Przepraszam za późną odpowiedź, jestem nowy na tej stronie, więc nie jestem obeznany ze wszystkimi funkcjami
rubyhui520

W innych językach

Ta strona jest w innych językach

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