ฉันผลักดัน <form>
ไปยังแฟ้ม HTML โดย JS แฟ้มแล้ว addEventListener ต้องแบบฟอร์มแต่ข้อผิดพลาดเกิดขึ้นระหว่างกลายเป็น:
Uncaught TypeError:ไม่สามารถอ่านคุณสมบัติของโพรโทคอล aimcomment(การอ่าน'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()
})