将元素添加到数组时,Javascript未定义错误

时间:2018-09-22 13:21:52

标签: javascript

我有一个Json数组,正在解析为javascript对象数组。

btn.addEventListener("click", function() {
  var request = new XMLHttpRequest();
  request.open('GET', 'http://localhost:8084/RestandJson/api/Person');
  request.onload = function() {
    var data = JSON.parse(request.responseText);
    // renderhtml(data);
    addPerson(data);
  };
  request.send();
});

我做了一个addPerson函数,将用户定义的对象添加到列表中。

addPerson = (data) => {
  var fName = document.getElementById("fname");
  var lName = document.getElementById("lname");
  var age = document.getElementById("age");
  var id = data.pop()+1;
  const person = {fName, lName, age, id};
  data.add(person);
}

调用该函数时,我得到“未定义addPerson”错误。为什么会这样?

这是我的整个文件:

var btn = document.getElementById("btn");
var root = document.getElementById("root");


btn.addEventListener("click", function() {
    var request = new XMLHttpRequest();
    request.open('GET', 'http://localhost:8084/RestandJson/api/Person');
    request.onload = function(){
      var data = JSON.parse(request.responseText);
      //renderhtml(data);
      addPerson(data);

    };
    request.send();

});



renderhtml = (data) => {
let htmlString = " ";

for(i = 0; i < data.length; i++){
    htmlString += "<p> " + data[i].fName +" " +  data[i].lName + "</p>"
}



addPerson = (data) => {
    var fName = document.getElementById("fname");
    var lName = document.getElementById("lname");
    var age = document.getElementById("age");
    var id = data.pop()+1;
    const person = {fName, lName, age, id};
    data.push(person);

}



root.insertAdjacentHTML('beforeend', htmlString);
}

2 个答案:

答案 0 :(得分:4)

这是因为您没有正确关闭renderHTML函数,应该是这样的:

renderhtml = (data) => {
  let htmlString = " ";

  for(i = 0; i < data.length; i++){
      htmlString += "<p> " + data[i].fName +" " +  data[i].lName + "</p>"
  }
} // <-- Add closing bracket to renderHTML function here

addPerson = (data) => {
  var fName = document.getElementById("fname");
  var lName = document.getElementById("lname");
  var age = document.getElementById("age");
  var id = data.pop()+1;
  const person = {fName, lName, age, id};
  data.push(person);
}

答案 1 :(得分:1)

尝试将整个addPerson函数移至renderhtml函数之外,这很可能是因为addPerson函数位于renderhtml函数内部