Unable to edit array inside of function

时间:2016-07-28 20:25:44

标签: javascript arrays function

I am trying to add (push) an element to a global array inside of a function with no luck. The function is called by an addEventListener() if that's at all helpful.

var cars = ["Saab", "Volvo", "BMW"];
function addInfo(){
    cars.push(document.getElementById("new_car").value);
}

//add listener
document.getElementsByClassName("add")[0].addEventListener("click", addInfo());

This is resulting in the error:

Uncaught SyntaxError: Unexpected identifier

How can I store all newly submitted items to keep a running tally?

1 个答案:

答案 0 :(得分:6)

addEventListener expects second argument(listener) as function-expression,

var cars = ["Saab", "Volvo", "BMW"];

function addInfo() {
  var elem = document.getElementById("new_car");
  cars.push(elem.value);
  elem.value = '';
  elem.focus();
  console.log(cars);
}
document.getElementsByClassName("add")[0].addEventListener("click", addInfo);
<input type="text" id="new_car" autofocus>
<br>
<br>
<input type="button" value="Add" class="add">