The first part of the code is working correctly, but now that each button appears, how do i add functionality to each of them? currently the only button which does something when pressed is always the last one, the rest do nothing.
Change it to
{
var output = "";
var data = JSON.parse(e.target.responseText);
for(var i=0; i<data.length; i++)
{
output = data[i].title + ' ';
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
button.innerHTML = "Download";
p.appendChild(button);
div.appendChild(p);
button.addEventListener ("click", () =>
{
alert("Test");
});
}
}
You are adding the below code out side the for loop
button.addEventListener ("click", () =>
{
alert("Test");
} );
Keep the above code inside the for loop. So that for each button the event listener will be added.
Another way to approach this would be to add the callback function to the onclick
variable of the elements prototype:
function doStuff() {
var output = "";
var data = JSON.parse(e.target.responseText);
for (var i = 0; i < data.length; i++) {
output = data[i].title + ' ';
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
button.innerHTML = "Download";
// Adds the callback function here
button.onclick = () => {
// fill in your arrow function here...
alert("Test");
};
p.appendChild(button);
div.appendChild(p);
};
}
doStuff();
Here is a jsFiddle
You should use event delegation for dynamically added elements
// sample data var data = [{ title: 'one' }, { title: 'two' },{ title: 'three' }]; var output = ""; for (var i = 0; i < data.length; i++) { var output = data[i].title + " "; var p = document.createElement("p"); var div = document.getElementById("response"); var textNode = document.createTextNode(output); p.appendChild(textNode); var button = document.createElement("button"); // added output to button text for identification button.innerHTML = output + " Download"; p.appendChild(button); div.appendChild(p); } // Get the parent element, add a click listener document.getElementById("response").addEventListener("click", function(e) { // e.target is the clicked element! // If it was a button if (e.target && e.target.nodeName == "BUTTON") { // Button found! Output the identifying data! // do other work on click document.getElementById("display").innerHTML = e.target.innerHTML + " Clicked"; } });
<div id="response"></div> <div id="display">Display</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.