0

I want to add eventlisnter to this HTML button that im creating, ive tried this method but it doesnt seem to work.

for (i in posts) {

    fetch(`http://127.0.0.1:8000/api/blogs/${posts.pk}`)
        .then((resp) => resp.json())
        .then((data) => {

            var blogs = `
            <div class = "center-div-row box-margin">
                    <div style="flex:2">
                        <h5>${data.title}</h5>
                        <hr>
                    </div>
                    <div style="flex:1">
                        <p>${data.body}</p>
                    </div>
                    <div style="flex:1">
                        <p>${data.created}</p>
                    </div>
                    <button class="edit-btn">Edit</button>
                    <button>Delete</button>
                </div>       
                `
        })
}

This is the method ive tried

            display.insertAdjacentHTML('beforeend', blogs)
            var editBtn = document.getElementsByClassName("edit-btn")[i]

            editBtn.addEventListener("click", (function (blogs) {
                return function () {
                    editPost(blogs)
                }
            })(posts[i]))

But it doesnt work. Any help would be appretiated :D

  • You need to solve the problem of `i` changing for the callback to `fetch.then` not just to `addEventListener` – Quentin Jul 18 '20 at 20:36
  • How do i do that? –  Jul 18 '20 at 20:37
  • Either the same way you already used, or the easier methods suggested on answers to the duplicate question. – Quentin Jul 18 '20 at 20:38
  • ive added the last code after the fetch call, is that what you mean, when i do that only the last button is clickable –  Jul 18 '20 at 20:41

0 Answers0