如果通过这个js文件将元素推送到html,如何将EventListener添加到html元素



我通过JS文件将<form>推送到HTML文件中,然后将EventListener添加到该表单中,但出现错误:未捕获的类型错误:无法读取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()
})

您需要使用事件委派,其中侦听器连接到父组件,该组件捕获子元素中的事件;冒泡";DOM。

// Adds a new form to the page
function addForm() {
const html = `
<form id="form">
<label>Provide The Following Words</lable>
<input />
<button type="submit" id="submit">Read Story</button>
<code id="result"></code>
</form>
`;
// Add the new HTML to the container
container.insertAdjacentHTML('beforeend', html);
}
function handleClick(e) {
// In this example we just want to
// to log the input value to the console
// so we first prevent the form from submitting
e.preventDefault();
// Get the id of the submitted form and
// use that to get the input element
// Then we log the input value
const { id } = e.target;
const input = document.querySelector(`#${id} input`);
console.log(input.value);
}
// Cache the container, and add the listener to it
const container = document.querySelector('#container');
container.addEventListener('submit', handleClick, false);
// Add the form to the DOM
addForm();
<div id="container"></div>

最新更新