我把一个 <form>
为HTML文件通过JS文件,然后addEventListener以这种形式而是一个错误事实证明:
未捕获的类型错误:不能读性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()
})