Я нажал на <form>
в HTML-файл с помощью файла JS, а затем добавьте в эту форму элемент списка событий, но получается ошибка:
Неперехваченная ошибка типа: Не удается прочитать свойства 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()
})