【发布时间】: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