Issue
Using JS, I'm adding buttons to a div by looping over a JSON list. When a button is pressed, a request needs to be made. The request is different for each button.
// example json object for button
obj = {
"name": "Test1",
"id": 15,
"link": "http://example.com"
};
// js to make button
table = document.getElementById('div-list');
button = document.createElement("button");
button.addEventListener("click", function() {
data = {
'id': obj.id
}
fetch(obj.link, {
method: 'POST',
body: JSON.stringify(data)
})
});
table.appendChild(button);
You can see the obj.id
and obj.link
. That is where the info from the json object needs to go. However, this doesn't work because the function is run when clicked, so the variable obj
won't exist anymore. So I basically need to store the JSON in the button
element so that when the button is clicked, it can get it's info.
Is there some way to allow that button-click-function access to "it's data" in order for it to determine where to send it's request to?
Solution
If you want to store data on an element you create, you can use the data attribute, for example
<button data-myid="3"></button>
After clicking the button you can get that data back with
event.target.dataset.myid
Answered By - Kokodoko
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.