按钮单击不加载数组的第一个元素



我希望用户能够单击一个按钮,然后在每次按下enter键时移动一组引号。我目前拥有的是点击按钮将数组加载到函数中,enter键在数组的每个元素中移动,但问题是通过初始按钮点击来获得屏幕上显示的第一个引号。我需要第一个报价出现在按钮点击。就目前情况来看,点击按钮只是为了让我的功能正常工作。我为纠正这一点所做的任何尝试都会导致每次按下enter键时都会调用该函数(这与我想要的结果并不接近(。如有任何建议,我们将不胜感激。

const quotes = [0, 1, 2, 3];
function runFunction(v){
document.body.addEventListener('keydown', function(e){
if ( e.keyCode == 13 && v.length > 0) {
let randNum = Math.floor(Math.random() * v.length);
let num = v[randNum];
v.splice(randNum, 1);
e.preventDefault();
switch (num){
case 0:
document.querySelector('.quote').textContent = "America will never be destroyed from the outside";                                   document.querySelector('.author').innerHTML = 'Abraham Lincoln';
break;
case 1: 
document.querySelector('.quote').textContent = 'Imagination is more important than knowledge.';
document.querySelector('.author').textContent = 'Albert Einstein';
break;
case 2:
document.querySelector('.quote').textContent = "Have no fear of perfection, you'll never reach it."
document.querySelector('.author').textContent = 'Salvador Dali';
break;
case 3: 
document.querySelector('.quote').textContent = "We don't make mistakes, just happy little accidents.";
document.querySelector('.author').textContent = 'Bob Ross';
break;
}
} 
});
}
<div class="quote"> Quote </div>
<div class="author"> Author </div>
<button onclick="runFunction(quotes)"> Get Quotes </button>

让我们将代码拆分为两个函数:

  1. onEnter()
    这里我们将设置第一个引号,并为enter添加事件侦听器

  2. setQuote()
    将设置新报价并将其从列表中删除的实际代码

然后我们将onClick更改为新的onEnter函数:onclick="onEnter()"

示例:

const quotes = [0, 1, 2, 3];
function onEnter() {
// Set the first one
setQuote();

// Now add eventListener for ENTER key
document.body.addEventListener('keydown', function(event){
if ( event.keyCode == 13 && quotes.length > 0) {
setQuote();
} 
});
}
function setQuote() {
let randNum = Math.floor(Math.random() * quotes.length);
let num = quotes[randNum];
quotes.splice(randNum, 1);
switch (num){
case 0:
document.querySelector('.quote').textContent = "America will never be destroyed from the outside";
document.querySelector('.author').innerHTML = 'Abraham Lincoln';
break;
case 1: 
document.querySelector('.quote').textContent = 'Imagination is more important than knowledge.';
document.querySelector('.author').textContent = 'Albert Einstein';
break;
case 2:
document.querySelector('.quote').textContent = "Have no fear of perfection, you'll never reach it."
document.querySelector('.author').textContent = 'Salvador Dali';
break;
case 3: 
document.querySelector('.quote').textContent = "We don't make mistakes, just happy little accidents.";
document.querySelector('.author').textContent = 'Bob Ross';
break;
}
}
<div class="quote"> Quote </div>
<div class="author"> Author </div>
<button onclick="onEnter()"> Get Quotes </button>

最新更新