on click get the value from array

问题: 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>

  • 发表于 2019-04-01 11:29
  • 阅读 ( 211 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除