Jak addEventListener k html prvku, pokud prvek je tlačen do html přes to js souboru?

0

Otázka

Strčil jsem <form> soubor HTML do JS souboru, a pak addEventListener k této formě ale chyba dopadá: Uncaught TypeError: Cannot read vlastnosti null (reading 'addEventListener').

Předpokládám, že je, protože tento JS souboru je spojen přímo do HTML souboru, což znamená, že JS by mohl být načten před <form>.

Může někdo prosím, řekněte mi, jak vyřešit tento problém?

JS kódy jsou níže:

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

Nejlepší odpověď

1

Musíte použít událost delegace , kde posluchač je připojen k nadřazené součásti, které zachycuje události ze sociální prvky, jako jsou "bubble up" 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

Ahoj Andy! Díky za pomoc, událost delegace opravdu funguje!!
rubyhui520

NP Andy! Omlouvám se za pozdní reakci asI jsem se na tento nový web proto nejsem obeznámen se všemi funkcemi
rubyhui520

V jiných jazycích

Tato stránka je v jiných jazycích

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