You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为JS动态插入HTML的元素绑定addEventListener事件?

问题根因

你的判断准确,报错核心是const $form = document.getElementById('form')这行代码在JS文件加载时就同步执行了,而id为form的元素是点击$start按钮后才动态生成插入DOM的,此时DOM中不存在该元素,$form为null,调用addEventListener自然触发报错。


解决方案

方案1:将事件绑定移到动态元素生成之后

把form的submit绑定逻辑放到$container插入form代码的语句之后,此时form已经存在于DOM中,可以正常获取绑定:

// skip to the input fields
$start.addEventListener('click', function(){
    $chooseStory.remove()

    const inputs = []
    
    inputs.push(`
        <form id="form">
        <label>Provide The Following Words</label>
    `)

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

    // form绑定逻辑移到此处,此时form已经插入DOM
    const $form = document.getElementById('form')
    $form.addEventListener('submit', function(e){
      e.preventDefault()
      // 后续表单处理逻辑写在这里
    })
})

方案2:使用事件委托(更推荐)

不需要等待元素生成,直接给form上层稳定存在的父元素(比如$container、document)绑定submit事件,通过事件冒泡捕获触发事件,也能避免多次点击按钮导致的重复绑定问题:

// 直接给上层稳定元素绑定submit事件,不用等待form生成
document.addEventListener('submit', function(e){
  // 判定触发事件的是目标form
  if(e.target.id === 'form') {
    e.preventDefault()
    // 后续表单处理逻辑写在这里
  }
})

// skip to the input fields
$start.addEventListener('click', function(){
    $chooseStory.remove()

    const inputs = []
    
    inputs.push(`
        <form id="form">
        <label>Provide The Following Words</label>
    `)

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

内容的提问来源于stack exchange,提问作者rubyhui520

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:54:07