[因此,当用户单击按钮排序或反向时,我试图对数字数组进行排序,而我的按钮名称分别是#sort-cards和#reverse-cards。我觉得这很简单,我很想念,但我只是无法弄清楚到底是什么。
(function () {
var cardElements, cardValues; // Do not declare more variables here.
// WRITE CODE HERE TO MAKE THE #cards ELEMENT WORK
//Get an array of all div elements inside the #cards element.
cardElements = Array.from(document.querySelectorAll('#cards div'));
//Initialize the cardValues variable as an empty array.
cardValues = [];
//Use a forEach loop to iterate through each of the div elements (the cards) one by one.
cardElements.forEach(function (cardElements) {
//Generate a card value, a random integer between 1 and 99.
cardElements.textContent = Math.floor(Math.random() * 99) + 1;
//Push it onto the end of the cardValues array and put it in the current div element.
cardValues.push(cardElements);
//Create an event handler that moves the card to the right end whenever it is clicked, leaving the other cards in the same order, and outputs all the new card values to the card divs.
//cardElements.addEventListener('click', function() {
//}
//Do things when the sort button is clicked
document.querySelector('#sort-cards').addEventListener('click', function () {
cardElements.sort(function (a, b){
return a - b;
});
});
//Do things when the reverse button is clicked.
document.querySelector('#reverse-cards').addEventListener('click', function () {
cardElements.reverse();
});
});
}());
您正在cardElements
回调中隐藏forEach
变量。另外,一次添加事件监听器,而不是为每张卡添加一次。尝试将其重命名为cardElement
,如下所示:
(function () {
var cardElements, cardValues; // Do not declare more variables here.
// WRITE CODE HERE TO MAKE THE #cards ELEMENT WORK
//Get an array of all div elements inside the #cards element.
cardElements = Array.from(document.querySelectorAll('#cards div'));
//Initialize the cardValues variable as an empty array.
cardValues = [];
//Use a forEach loop to iterate through each of the div elements (the cards) one by one.
cardElements.forEach(function (cardElement) {
//Generate a card value, a random integer between 1 and 99.
cardElement.textContent = Math.floor(Math.random() * 99) + 1;
//Push it onto the end of the cardValues array and put it in the current div element.
cardValues.push(cardElement);
//Create an event handler that moves the card to the right end whenever it is clicked, leaving the other cards in the same order, and outputs all the new card values to the card divs.
//cardElements.addEventListener('click', function() {
//}
});
//Do things when the sort button is clicked
document.querySelector('#sort-cards').addEventListener('click', function () {
cardElements.sort(function (a, b){
return a - b;
});
});
//Do things when the reverse button is clicked.
document.querySelector('#reverse-cards').addEventListener('click', function () {
cardElements.reverse();
});
}());