问题:
I want to get the value from array on click event. How can i achieve this. Tried some code did not work.
var array = ['jane', 'alax', 'russell', 'max'];
var newArr = [];...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I want to get the value from array on click event. How can i achieve this. Tried some code did not work.
var array = ['jane', 'alax', 'russell', 'max'];
var newArr = [];
function myFunction() {
for(var i=0; i<=array.length; i++) {
console.log(array);
newArr.push(array[i]);
}
}
document.getElementById("res").innerHTML = newArr;
It should add first jane on first click then second click add alax and so on.
回答1:
In your current scenario, it's iterating over all elements on each click. To make it like one by one use a counter variable which increments on each click until it reaches array length, use it for getting the element to push and finally updates the HTML within the event handler to update on each click.
var array = ['jane', 'alax', 'russell', 'max'];
var newArr = [];
// variable for keep track of clicks
var c = 0;
function myFunction() {
// check value of counter
if (c < array.length) {
// push value and increment counter
newArr.push(array[c++])
// set html
document.getElementById("res").innerHTML = newArr;
}
}
<div id="res"></div>
<button onclick="myFunction()">click</button>
回答2:
var i = 0
var array = ['jane', 'alax', 'russell', 'max'];
var newArr = [];
function onClick(){
console.log(array[i])
newArr.push(array[i])
i++
};
回答3:
We can do this by setting an initialValue
of 0
to point to the first element of the array, then on each successive invocation we increment the initialValue
by 1 to fetch the next element into the new array display
until we exhaust the array.
After adding the element in the display
array, we simply use Array.join
to join all the values of the array into a comma separated string.
let clickHandler = (function(){
const array = ['jane', 'alax', 'russell', 'max'];
let initialValue = 0;
let display = [];
function clickHandler(){
display = initialValue < array.length ? display.concat(array[initialValue++]): display;
document.getElementById("res").textContent = display.join();
}
return clickHandler;
})();
<button onclick="clickHandler()">Click here!</button>
<span id="res"></span>