Como addEventListener a um elemento html se o elemento é deslocado para o html através deste arquivo js?

0

Pergunta

Puxei <form> para o arquivo HTML, JS, arquivo e, em seguida, addEventListener para esse formulário, mas um erro acontece: Não identificada TypeError: não é Possível ler as propriedades de null ('leitura addEventListener').

Eu suponho que é porque este arquivo JS está vinculada diretamente para o arquivo HTML que significa que a JS pode ser carregado antes do <form>.

Alguém por favor pode me dizer como resolver isso?

A JS códigos abaixo:

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

Melhor resposta

1

Você precisa usar o evento de delegação em um ouvinte está ligada a um componente pai que captura eventos de elementos filho que eles "bolha" do 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

Oi Andy! Obrigado por me ajudar lá fora, o evento delegação realmente funciona!!
rubyhui520

NP Andy! Desculpe pela demora de responder asI sou novo nesse site, portanto, eu não estou familiarizado com todas as funções
rubyhui520

Em outros idiomas

Esta página está em outros idiomas

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