Ako addEventListener na html element, ak prvok zatlačený do html prostredníctvom tohto js súbor?

0

Otázka

Som tlačil <form> HTML súbor JS súbor, a potom addEventListener k tejto forme, ale chybové ukáže: Uncaught TypeError: nemôžem čítať vlastnosti null (čítanie "addEventListener').

Predpokladám, že je to preto, že tento JS súbor je prepojené priamo s HTML súbor, ktorý znamená, JS môže byť vložený pred <form>.

Môže mi niekto prosím, povedzte mi, ako vyriešiť tento problém?

JS kódy sú uvedené nižšie:

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

Najlepšiu odpoveď

1

Musíte použiť prípade delegácia , v ktorej poslucháč je pripojený na materský komponent, ktorý zachytáva udalosti z dieťa prvky, ako sa "bublina hore" 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! Vďaka za pomoc mi tam, udalosti delegácia naozaj funguje!!
rubyhui520

NP Andy! Ospravedlňujeme sa za neskoré reagovať asI som nový na tejto stránke preto nie som oboznámený so všetkými funkciami
rubyhui520

V iných jazykoch

Táto stránka je v iných jazykoch

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