【问题标题】:How to addEventListener to an html element if the element is pushed to the html through this js file?如果通过此js文件将元素推送到html,如何将EventListener添加到html元素?
【发布时间】:2021-12-31 03:23:50
【问题描述】:

我通过 JS 文件将<form> 推送到 HTML 文件,然后将事件监听器添加到此表单,但出现错误: 未捕获的 TypeError:无法读取 null 的属性(正在读取“addEventListener”)。

我认为这是因为这个 JS 文件直接链接到 HTML 文件,这意味着 JS 可能在 <form> 之前加载。

谁能告诉我如何解决这个问题?

JS代码如下:

// 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()
})

【问题讨论】:

  • 由于元素是动态创建的,需要使用事件委托来处理事件

标签: javascript typeerror addeventlistener


【解决方案1】:

您需要使用event delegation,其中一个侦听器附加到父组件,该组件在子元素“冒泡”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();
&lt;div id="container"&gt;&lt;/div&gt;

【讨论】:

  • 嗨,安迪!谢谢你帮我,事件委托真的很管用!!
  • NP 安迪!抱歉回复晚了,因为我是新来的这个网站,所以我对所有的功能都不熟悉?
猜你喜欢
  • 2021-10-10
  • 2021-10-09
  • 2023-01-26
  • 1970-01-01
  • 1970-01-01
  • 2023-01-16
  • 1970-01-01
  • 2021-01-04
  • 2016-01-01
相关资源
最近更新 更多