xButton.setAttribute 不是函数错误

我有一个函数可以将 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;

      }


主要问题是 xButton,任何帮助表示赞赏。


慕婉清6462132
浏览 167回答 3
3回答

慕妹3242003

var xButton = document.createElement("BUTTON");xButton.innerHTML = "x";xButton.setAttribute("onclick", `deleteElement('${jsonPayload[i].id}')`);// then at the end, instead of "fourthColumn.innerHTML = xButton;" you should do thisfourthColumn.appendChild(xButton);

偶然的你

您需要使用createElement来创建一个按钮,因为目前它只是一个字符串..var xButton = document.createElement("button");xButton.innerHTML = "x";xButton.setAttribute("onclick", `deleteElement('${jsonPayload[i].id}')`);

斯蒂芬大帝

您需要使用正确的代码创建它。另外我建议你试试JQuery。var button = document.createElement("button");button.innerHTML = "Do Something";var body = document.getElementsByTagName("body")[0];body.appendChild(button);button.addEventListener ("click", function() {&nbsp; alert("test");});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript