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?
答案 0 :(得分:6)
addEventListener
expects second argument(listener
) asfunction-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">