У меня есть функция, которая форматирует элементы в файле JSON в таблицу.
Таблица работает нормально, но сейчас я пытаюсь реализовать кнопку в другом столбце, которая удаляет указанный элемент из файла.
Но когда я это сделал, появляется ошибка: Uncaught (in promise) TypeError: xButton.setAttribute is not a function
Вот мой код:
async function table() {
let response = await fetch('/tasks', {
method: "GET",
headers: {
'Content-Type': 'application/json'
}
});
let jsonPayload = await response.json();
var table = document.getElementById("tableBody");
tableBody.innerHTML = "";
for(var i = jsonPayload.length - 1; i > -1; i--) {
var row = tableBody.insertRow(0);
var firstColumn = row.insertCell(0);
var secondColumn = row.insertCell(1);
var thirdColumn = row.insertCell(2);
var fourthColumn = row.insertCell(3);
var xButton = '<button>x</button>';
xButton.setAttribute("onclick", `deleteElement('${jsonPayload[i].id}')`);
firstColumn.innerHTML = jsonPayload[i].id;
secondColumn.innerHTML = jsonPayload[i].desc;
thirdColumn.innerHTML = jsonPayload[i].importance;
fourthColumn.innerHTML = xButton;
}
}
Это код для удаления элемента
//function which deletes a task.
function deleteElement() {
//Variable id is the number submitted in the input form to Delete tasks
var id = document.getElementById("deleteId").value;
//This is the url that is fetched with the variable id which deletes the function using the code from the backend.
var url = "/tasks/"+id;
//isNan checks whether id is not a number
if (isNaN(id)) {
//If it is not a number the error message is displayed.
alert("The value inputted must be a number!");
//Returns out of the function without proceeding
return;
}
//Fetches /tasks, with the DELETE method
fetch(url, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
});
//display(); Calls the display function at the end to display the tasks again without the deleted url.
display();
}
Основная проблема с xButton, любая помощь приветствуется.