首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >每次使用javascript和jquery单击按钮时更改文本

每次使用javascript和jquery单击按钮时更改文本
EN

Stack Overflow用户
提问于 2022-08-20 13:05:17
回答 1查看 37关注 0票数 0

我有一个引号的列表,每次我点击这个按钮,我希望它转到一个新的引号。有人能解释一下这里出了什么问题吗?我该怎么解决呢?

代码语言:javascript
复制
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);
}

EN

回答 1

Stack Overflow用户

发布于 2022-08-20 13:11:48

我看到的唯一问题是,您的代码似乎没有使用nextQuote索引从quotes数组中检索元素。您也不会在任何地方调用myLost(),但我假设问题中的示例忽略了这一点。

还请注意,可以简化数组定义,并且可以使用模块化运算符访问数组,而无需将索引重置为0。试试这个:

代码语言:javascript
复制
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();
代码语言:javascript
复制
<button type="button" id="buton">Get quote</button>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73426941

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档