无法在导入元素节点上添加事件侦听器
我正在获取来自API的帖子列表,并在网页上显示它们。现在,有一个与每个帖子关联的删除按钮,单击时应删除帖子。
index.html
<template id="single-post">
<li class="post-item">
<h2></h2>
<p></p>
<button>DELETE</button>
</li>
</template>
<ul class="posts"></ul>
app.js
const listElement = document.querySelector('.posts');
const postTemplate = document.getElementById('single-post');
const listOfPosts = await sendHttpRequest(
'GET',
'https://jsonplaceholder.typicode.com/posts'
);
// listOfPosts is already in parsed format
for (const post of listOfPosts) {
const postEl = document.importNode(postTemplate.content, true);
postEl.querySelector('h2').textContent = post.title.toUpperCase();
postEl.querySelector('p').textContent = post.body;
listElement.append(postEl);
const btn = postEl.querySelector('button');
console.log(btn, postEl);
btn.addEventListener('click', () => {
postEl.remove();
});
}
上面的代码仅获取第一篇文章并抛出
uck offult(在承诺中)TypeError:无法读取null的属性(读取'addeventListener') 在htmlbuttonelement.fetchposts
上
删除事件侦听器时,代码正常工作。
我想这与 exixpnode
方法有关,因为我已经使用进行了类似的操作CreateElement
他们的工作正常
编辑
我做了一些尝试。 API返回的JSON帖子对象也由ID字段组成。因此,我基本上将ID添加到正在创建的每个按钮中。
另一件事是我使用事件委托删除()单击其按钮的 li
。
而且非常令人惊讶的是它可以使用
const listElement = document.querySelector('.posts');
const postTemplate = document.getElementById('single-post');
const listOfPosts = await sendHttpRequest(
'GET',
'https://jsonplaceholder.typicode.com/posts'
);
// listOfPosts is already in parsed format
for (const post of listOfPosts) {
const postEl = document.importNode(postTemplate.content, true);
postEl.querySelector('h2').textContent = post.title.toUpperCase();
postEl.querySelector('p').textContent = post.body;
postEl.querySelector('button').id = post.id; // HERE
listElement.append(postEl);
}
// delete the li element
listElement.addEventListener('click', (event) => {
if(event.target.tagName === 'BUTTON') {
console.log(event.target);
event.target.parentElement.remove();
}
})
单击第一个列表帖子的删除按钮时,它会安装
<button id="1">DELETE</button>
并删除该项目。
该基础证明该按钮标签肯定在那里,因为我们能够查询选择并设置其ID。
奇怪的是,当安慰时,它显示 null
。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码错误在此处:
错误消息阐明
BTN
是null
,这意味着Postel.querySelector('button')
返回> null
,这意味着在postel
中没有按钮
标记。您将需要仔细查看
document.importnode(posttemplate.content,true)
的结果,然后查看其中包含的内容。您会看到它不包含按钮
标签。因此,要么未添加按钮
,在这种情况下,您需要调整exixtnode
,或者,该按钮不是button
tag,但是,例如&lt; input type =“ button” value =“ foo”&gt;
,例如其他内容。Your code errors out here:
The error message clarifies that
btn
isnull
, which means thatpostEl.querySelector('button')
returnednull
, which means that there is nobutton
tag insidepostEl
.You will need to carefully look at the result of
document.importNode(postTemplate.content, true)
and see what it contains. You will see that it does not contain abutton
tag. So, either thebutton
was not added, in which case you will need to adjustimportNode
, or, the button is not abutton
tag, but something else, like<input type="button" value="foo">
for example.