Öğe bu js dosyası aracılığıyla html'ye itilirse, bir html öğesine eventlistener nasıl eklenir?

0

Soru

Ben ittim <form> HTML dosyasına JS dosyası ve ardından bu forma addEventListener ekleyin, ancak bir hata ortaya çıkıyor: Yakalanmamış TypeError: Null özellikleri okunamıyor ('addEventListener' okunuyor).

Bunun nedeni, bu JS dosyasının doğrudan HTML dosyasına bağlı olmasıdır, bu da js'nin yüklenmeden önce yüklenebileceği anlamına gelir. <form>.

Herkes bu çözmek için nasıl bana söyleyebilir misiniz?

JS kodları aşağıda verilmiştir:

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

En iyi cevabı

1

Bir dinleyicinin, dom'u "kabarcıklarken" alt öğelerden olayları yakalayan bir üst bileşene bağlı olduğu olay temsilciliğini kullanmanız gerekir.

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

Merhaba Andy! Orada bana yardım ettiğin için teşekkürler, etkinlik delegasyonu gerçekten işe yarıyor!!
rubyhui520

NP Andy! Geç yanıt verdiğim için özür dilerim asI bu web sitesinde yeniyim, bu nedenle tüm işlevlere aşina değilim
rubyhui520

Diğer dillerde

Bu sayfa diğer dillerde

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