我有一个引号的列表,每次我点击这个按钮,我希望它转到一个新的引号。有人能解释一下这里出了什么问题吗?我该怎么解决呢?
function myLost() {
var quotes = new Array();
var nextQuote = 0;
quotes[0] = "Don't be so humble - you are not that great.";
quotes[1] = "Moral indignation is jealousy with a halo.";
quotes[2] = "Glory is fleeting, but obscurity is forever.";
quotes[3] = "The fundamental cause of trouble in the world is that the stupid are cocksure while the intelligent are full of doubt.";
quotes[4] = "Victory goes to the player who makes the next-to-last mistake.";
quotes[5] = "His ignorance is encyclopedic";
quotes[6] = "If a man does his best, what else is there?";
quotes[7] = "Political correctness is tyranny with manners.";
quotes[8] = "You can avoid reality, but you cannot avoid the consequences of avoiding reality.";
quotes[9] = "When one person suffers from a delusion it is called insanity; when many people suffer from a delusion it is called religion."
function buttonClickHandler() {
nextQuote++;
// roll back to 0 if we reach the end
if (nextQuote >= quotes.length) {
nextQuote = 0;
}
}
document.getElementById('buton').addEventListener("click", buttonClickHandler, false);
}
发布于 2022-08-20 13:11:48
我看到的唯一问题是,您的代码似乎没有使用nextQuote索引从quotes数组中检索元素。您也不会在任何地方调用myLost(),但我假设问题中的示例忽略了这一点。
还请注意,可以简化数组定义,并且可以使用模块化运算符访问数组,而无需将索引重置为0。试试这个:
function myLost() {
let nextQuote = 0;
let quotes = [
"Don't be so humble - you are not that great.",
"Moral indignation is jealousy with a halo.",
"Glory is fleeting, but obscurity is forever.",
"The fundamental cause of trouble in the world is that the stupid are cocksure while the intelligent are full of doubt.",
"Victory goes to the player who makes the next-to-last mistake.",
"His ignorance is encyclopedic",
"If a man does his best, what else is there?",
"Political correctness is tyranny with manners.",
"You can avoid reality, but you cannot avoid the consequences of avoiding reality.",
"When one person suffers from a delusion it is called insanity; when many people suffer from a delusion it is called religion."
];
function buttonClickHandler() {
let quote = quotes[nextQuote % quotes.length];
console.log(quote);
nextQuote++;
}
document.querySelector('#buton').addEventListener("click", buttonClickHandler, false);
}
myLost();<button type="button" id="buton">Get quote</button>
https://stackoverflow.com/questions/73426941
复制相似问题