JavaScript Intetadjacenthtml()不起作用

发布于 2025-02-12 16:56:50 字数 1140 浏览 3 评论 0原文

全部 我试图使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

习ぎ惯性依靠 2025-02-19 16:56:51

只需在循环之外做:

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
    people.forEach((person, i) => {
        let html = `
        <li><a href=${person.homeworld} target="_blank">${person.name}</a></li>
        `
        ul.insertAdjacentHTML("afterbegin", html)

    })
    document.querySelectorAll("a").forEach(a => a.addEventListener('click', expandDetails))
    
})

function expandDetails(ev) {
    ev.preventDefault()
    console.log("ev.target", ev.target)
}
<ul id="list"></ul>

Just do it outside your loop:

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
    people.forEach((person, i) => {
        let html = `
        <li><a href=${person.homeworld} target="_blank">${person.name}</a></li>
        `
        ul.insertAdjacentHTML("afterbegin", html)

    })
    document.querySelectorAll("a").forEach(a => a.addEventListener('click', expandDetails))
    
})

function expandDetails(ev) {
    ev.preventDefault()
    console.log("ev.target", ev.target)
}
<ul id="list"></ul>

叫思念不要吵 2025-02-19 16:56:51

而不是所有列表项目上的听众使用事件委托。附加一个侦听器上ul元素,并在其“冒出” dom时从其子元素中听取事件。当ExpandDetails被称为检查事件是否来自列表项目中的锚点,然后记录结果。

const END_POINT = "https://swapi.dev/api/people/"

const ul = document.querySelector("ul")
ul.addEventListener('click', expandDetails);

function expandDetails(e) {
  if (e.target.matches('li a')) {
    e.preventDefault();
    console.log(e.target.textContent);
  }
}

fetch(END_POINT)
  .then(response => response.json())
  .then(data => {
    const people = data.results;
    people.forEach((person, i) => {
      const html = `
        <li>
          <a href=${person.homeworld}>${person.name}</a>
        </li>
        `
      ul.insertAdjacentHTML("afterbegin", html)
    });
  });
<ul id="list"></ul>

您可能会考虑的另一件事是创建HTML的数组,然后在将其添加到DOM之前加入。这样一来,您只会调用insertadjacenthtml 在所有html都已被编译而不是在循环的每一个迭代中。 (但是,请注意,此版本以与上一个示例相反的顺序打印列表项目,该示例可能是问题也可能不是问题的。 -us/doc/learn/javascript/asynchronous/promises#async_and_await“ rel =” nofollow noreferrer“> async/等待 使代码变得更加整洁。)

const END_POINT = "https://swapi.dev/api/people/"

const ul = document.querySelector("ul")
ul.addEventListener('click', expandDetails);

function expandDetails(e) {
  if (e.target.matches('li a')) {
    e.preventDefault();
    console.log(e.target.textContent.trim());
  }
}

async function main() {
  const response = await fetch(END_POINT);
  const { results } = await response.json();
  const html = results.map(person => {
    return `
      <li>
        <a href=${person.homeworld}>
          ${person.name}
        </a>
      </li>
      `
  });
  ul.insertAdjacentHTML('beforeend', html.join(''));
}

main();
<ul id="list"></ul>

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. When expandDetails is called check that the event is from an anchor in a list item, and then log the result.

const END_POINT = "https://swapi.dev/api/people/"

const ul = document.querySelector("ul")
ul.addEventListener('click', expandDetails);

function expandDetails(e) {
  if (e.target.matches('li a')) {
    e.preventDefault();
    console.log(e.target.textContent);
  }
}

fetch(END_POINT)
  .then(response => response.json())
  .then(data => {
    const people = data.results;
    people.forEach((person, i) => {
      const html = `
        <li>
          <a href=${person.homeworld}>${person.name}</a>
        </li>
        `
      ul.insertAdjacentHTML("afterbegin", html)
    });
  });
<ul id="list"></ul>

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 calling insertAdjacentHTML 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 used async/await to make the code a little neater.)

const END_POINT = "https://swapi.dev/api/people/"

const ul = document.querySelector("ul")
ul.addEventListener('click', expandDetails);

function expandDetails(e) {
  if (e.target.matches('li a')) {
    e.preventDefault();
    console.log(e.target.textContent.trim());
  }
}

async function main() {
  const response = await fetch(END_POINT);
  const { results } = await response.json();
  const html = results.map(person => {
    return `
      <li>
        <a href=${person.homeworld}>
          ${person.name}
        </a>
      </li>
      `
  });
  ul.insertAdjacentHTML('beforeend', html.join(''));
}

main();
<ul id="list"></ul>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文