JavaScript Intetadjacenthtml()不起作用
全部 我试图使用insertadjacenthtml()
来创建元素并使用AddeventListener()
添加事件。我认为下面的代码中没有一个合乎逻辑的问题,但是它无法正常工作(不是console.log())
我的代码如下:
const END_POINT = "https://swapi.dev/api/people/"
let ul = document.querySelector("ul")
fetch(END_POINT)
.then(response => response.json())
.then(data => {
let people = data.results
console.log(people)
people.forEach((person, i) => {
let html = `
<li><a href=${person.homeworld} target="_blank">${person.name}</a></li>
`
ul.insertAdjacentHTML("afterbegin", html)
function expandDetails(ev) {
ev.preventDefault()
console.log("fef")
console.log("ev.target", ev.target)
}
let a = document.querySelectorAll("a")[i]
a.addEventListener("click", expandDetails)
})
})
<ul id="list"></ul>
我觉得这大约是某物的延迟,并且应在某个地方添加settimeout()
。有建议吗?
all
I was trying to use insertAdjacentHTML()
to create elements and add events by using addEventListener()
.I don't think there was a logical problem in my code below, but it was not working (not console.log()ing)
My code was as below:
const END_POINT = "https://swapi.dev/api/people/"
let ul = document.querySelector("ul")
fetch(END_POINT)
.then(response => response.json())
.then(data => {
let people = data.results
console.log(people)
people.forEach((person, i) => {
let html = `
<li><a href=${person.homeworld} target="_blank">${person.name}</a></li>
`
ul.insertAdjacentHTML("afterbegin", html)
function expandDetails(ev) {
ev.preventDefault()
console.log("fef")
console.log("ev.target", ev.target)
}
let a = document.querySelectorAll("a")[i]
a.addEventListener("click", expandDetails)
})
})
<ul id="list"></ul>
I have a feeling it's about a delay of something and a setTimeout()
should be added somewhere. Any advice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需在循环之外做:
Just do it outside your loop:
而不是所有列表项目上的听众使用事件委托。附加一个侦听器上
ul
元素,并在其“冒出” dom时从其子元素中听取事件。当ExpandDetails
被称为检查事件是否来自列表项目中的锚点,然后记录结果。您可能会考虑的另一件事是创建HTML的数组,然后在将其添加到DOM之前加入。这样一来,您只会调用
insertadjacenthtml
在所有html都已被编译而不是在循环的每一个迭代中。 (但是,请注意,此版本以与上一个示例相反的顺序打印列表项目,该示例可能是问题也可能不是问题的。 -us/doc/learn/javascript/asynchronous/promises#async_and_await“ rel =” nofollow noreferrer“>async/等待
使代码变得更加整洁。)Instead of listeners on all list items use event delegation. Attach one listener to the
ul
element and have that listen to events from its child elements as they "bubble up" the DOM. WhenexpandDetails
is called check that the event is from an anchor in a list item, and then log the result.Another thing you might consider is creating an array of HTML and then
joining
it up before adding it to the DOM. That way you're only callinginsertAdjacentHTML
once after all the HTML has been compiled rather on every iteration of the loop. (Note, however, that this version prints the list items in the opposite order to the previous example which may or may not be an issue. I've also usedasync/await
to make the code a little neater.)