编辑:好的,我的解释不太好。我在HTML中添加了一个按钮。当您单击该按钮时,它会发出警报并要求用户输入问题和答案。但是...它不会将该阵列推入卡本身。

我已经一起破解了一个简单的javascript闪存卡程序。但是它会在页面加载后立即开始。如何使它从单击单个<button>开始?我尝试将整个代码包含在一个函数中,但是创建数组的用户输入不会传递给抽认卡,我想是因为它们是独立的函数。我可能解释得不好。但是我希望整个程序只需单击一个按钮即可运行。感谢您的帮助。

#flashcardFront {
    margin-top: 100px;
    margin-left: 400px;
    width: 300px;
    height: 50px;
    background-color: black;
    color: white;
    font-family: arial;
    font-size: 22px;
    text-align: center;
    padding: 50px 0;
    display: block;
}

a:link {
    text-decoration: none;
}

#number {
    color: red;
    position: relative;
    left: -120px;
    top: 30px;
}


<div>
    <button onclick='cards();'>button</button>
    <a id="flashcardFront" href="#" onclick="flashCards();"></a>
</div>


var myArray = [];

for (var i = 0; i < 2; i++) {              // # of loops
  myArray.push(prompt('Enter question ' + (i+1))); // push the value into the array
  myArray.push(prompt('Enter answer ' + (i+1))); // push the value into the array
}
/*var myArray = [
  "Q: What's my name?", 'A: Heck no.',
  'Q: My age?', "A: Cool kids don't say.",
  'Q: Fave rocker?', 'A: Paul Gilbert'
];*/
var myIndex = 0;

function renderQuestion(index) {
  // render number if index is even
  var str = myArray[index]
  if (index % 2 == 0) {
    str += '<br><span class="question-number">' + (index / 2 + 1) + '</span>'
  }
  return str
}

function flashCards() {
  var flashcardFront = document.getElementById('flashcardFront');
  flashcardFront.innerHTML = renderQuestion(myIndex);
  myIndex = (myIndex + 1) % (myArray.length);
}

flashCards()

最佳答案

我认为这里的问题是myIndex是全局的。第一次运行flashcards时,它将索引增加到数组的长度,因此,下次运行(在单击处理程序中)它已经在数组的末尾。在flashcards的开头将其设置为0。

08-19 05:08