单击并获取ArrayValue

时间:2018-09-06 07:17:00

标签: javascript

当我单击时,我想在数组中显示第一个值,再次单击,在数组中显示第二个值(增加一个...)

 const btn = document.querySelector('.btn');
    const content = document.querySelector('.content');
    
    btn.addEventListener('click',getArray);
    
    function getArray(event){
       const items = [10,20,30,40,50];
        

    }
<button class="btn">Array Index</button>
<div class="content">
    
    </div>

3 个答案:

答案 0 :(得分:0)

var items = [10,20,30,40,50];
var x = "";
var i = 0;

document.getElementById("btn").onclick = function() {
if( i < items .length) {
x += items [i++] + "<br>";
}
 document.getElementById("text").innerHTML = x;
}

<p id="text"></p>
<button id="btn">Result</button>

答案 1 :(得分:0)

这是使用generator function的一种可能方法。

const btn = document.querySelector('.btn');
const content = document.querySelector('.content');
const gen = getNextNumber();
    
btn.addEventListener('click',getArray);
    
function getArray(event){
   content.innerText = gen.next().value;
}
    
function *getNextNumber() {
    const items = [10,20,30,40,50];
    for(let i = 0; i < items.length; ++i) {
        yield items[i];
    }
}
<button class="btn">Array Index</button>
<div class="content">
    
</div>

答案 2 :(得分:-1)

我认为这符合您的需求:

const btn = document.querySelector('.btn');
const content = document.querySelector('.content');
let counter = 0; // Counter to access the index

btn.addEventListener('click', getArray);

function getArray() { // Removed 'event' here -> not necessary
  const items = [10, 20, 30, 40, 50];

  if (counter < items.length) { // Prevent getting "undefined"
    content.innerText = items[counter]; // Change the content of your div
    counter++; // Increase counter to get the next index
  }
}
<button class="btn">Array Index</button>
<div class="content"></div>

我将更改和添加内容添加到您的代码中作为注释