I want to add a JavaScript function via DOM to my Homepage. I am using a Json String to get the elements. Everything is running fine but I have an issue the Javascript function has always the same parameter and the parameter is not changing no matter which button i click. The paramater is alwys the last value "name" of the jso string. How to iterate the correct way through the json and build up the DOM document? here is my code
var jsonData = JSON.parse(jsonstring);
let element = document.getElementById("fi");
while (element.firstChild) {
element.removeChild(element.firstChild);
}
for (var i = 0; i < jsonData.files.length; i++) {
// Now create and append to iDiv
var innerNameDiv = document.createElement('div');
innerNameDiv.className = 'ccl ccu';
innerNameDiv.style.float = "left";
innerNameDiv.style.width = "45%";
innerNameDiv.innerHTML = " " + jsonData.files[i].name;
var innerFileSizeDiv = document.createElement('div');
innerFileSizeDiv.className = 'cct ccu';
innerFileSizeDiv.style.float = "left";
innerFileSizeDiv.style.width = "30%";
innerFileSizeDiv.textContent = jsonData.files[i].filesize;
var innerButtonDiv = document.createElement('div');
innerButtonDiv.className = 'ccr ccu';
innerButtonDiv.style.float = "left";
innerButtonDiv.style.width = "20%";
var innerButtonDelete = document.createElement("button");
innerButtonDelete.class = "b";
innerButtonDelete.innerText = "Del";
var filename = jsonData.files[i].name;
innerButtonDelete.addEventListener('click', () => {
deleteFile(filename)
});
innerButtonDiv.appendChild(innerButtonDelete);
element.appendChild(innerNameDiv);
element.appendChild(innerFileSizeDiv);
element.appendChild(innerButtonDiv);
console.log(jsonData.files[i].name + ":" + jsonData.files[i].filesize);
}
Json string is for example :
{"files":[{"name":"1","filesize":32},{"name":"2","filesize":32},{"name":"3","filesize":32},{"name":"4","filesize":32}]}
No matter which button I click it will be always with parameter 4 and not any different.