【问题标题】:change text every time button clicked每次单击按钮时更改文本
【发布时间】:2014-01-11 22:13:20
【问题描述】:

我搜索了很多,但找不到答案...

我有一个报价列表,每次单击按钮时,我都希望它转到新报价。 有人可以解释一下这里出了什么问题以及我应该如何解决它?

<script language="Javascript">    

    function buttonClickHandler() {

        var textField = document.getElementById("textField"); 

        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.";

        nextQuote++;
        textField.value = quotes[nextQuote];       
    }
</script>

我在互联网上找到了此代码,当我使用此代码时,它会在每次点击时更改文本。

        var currentValue = parseInt(textField.value);

        // Add one
       currentValue++;

        // Put it back with the new +1'd value
        textField.value = currentValue;
        var quotes = new Array();

我用于数组的代码几乎相同,但不会更改每次点击的文本。我需要为数组做些什么特别的事情吗?帮助!!

【问题讨论】:

  • 您可以无限期地使用poppush 的组合来旋转引号而不是维护计数器。
  • 你怎么打电话给buttonClickHandler?如果您每次都调用它,它会始终显示您的第一个报价,因为您每次都在初始化 nextQuote
  • 每次运行点击处理程序时,您都将nextQuote 重置为零。这使得报价 1 到 9 超重行李。
  • 检查这个:jsbin.com/OFIliHUs/1/edit
  • 我的意思是shiftpush,基本上是移位一个值,将它存储在一个var中,然后将它推到最后。

标签: javascript arrays button text


【解决方案1】:

它不会改变它,因为您在处理程序中声明了数组和索引,因此每次单击时都会在索引 1 处获得引号。在处理程序外部定义索引(以及数组)并在处理程序内部递增:

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() {
    var textField = document.getElementById("textField");
    textField.value = [++nextQuote];
}

【讨论】:

    【解决方案2】:

    因为每次调用函数nextQuote都会重新设置为0

    【讨论】:

      【解决方案3】:

      每次调用处理程序时,都将 nextQuote 赋值为 0。

      var nextQuote = 0;

      尝试这样做:

      var quotes = new Array();
          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.";
      
      var nextQuote = 0;
      var textField = document.getElementById("textField"); 
      
      
      function buttonClickHandler() {
          if(nextQuote < 9) {
              nextQuote++;
          } else {
              nextQuote = 0;
          }
          textField.value = quotes[nextQuote];
      }
      

      【讨论】:

        【解决方案4】:

        试试类似的东西

        var nextQuote = Math.floor((Math.random()*9)+1);

        而不是你的:

        var nextQuote =0;

        稍后将 9 更改为您的数组大小,并在您将所有值声明到数组中后添加它。

        【讨论】:

          【解决方案5】:

          不同之处在于有效的代码从 buttonClickHandler 外部获取要递增的值

          var currentValue = parseInt(textField.value);

          每次调用 buttonClickHandler 时重新初始化它的位置

          var nextQuote = 0;

          我认为如果你用这个声明替换它会起作用

          if (window.nextQuote == null) {
             window.nextQuote = 0 
          } else {
             window.nextQuote++
          }
          

          【讨论】:

            【解决方案6】:

            正如之前发布的答案已经说明的那样,问题是因为nextQuote 是在buttonClickHandler 内部定义的,因此每次函数完成执行时都会被销毁,并且每次函数开始时都会重新创建并初始化为0

            您似乎正在使用一些非常古老的教程学习 JavaScript,以下代码将展示如何将其重构为更现代的风格。

            &lt;script language="Javascript"&gt;&lt;script&gt; 标签的language attribute 很久以前就被弃用了。不要使用它。它被type 属性取代,但是don't use the type attribute either。只是一个普通的&lt;script&gt; 标签适用于所有浏览器,它们都默认使用 JavaScript,因为它是唯一一种作为客户端脚本语言获得任何牵引力的语言。

            <script>
            (function (document) { // Use a self-invoking function to keep our variables
                                   // out of the global scope
            
              "use strict"; // Force the browser into strict mode
            
              var nextQuote = 0, // instead of using separate var statements you can use
                                 // a comma to include all of your variable declarations
                                 // in one statement.
            
                /* Since we will be using the textField DOM element a lot, lets cache a
                   copy in a variable outside of the handler instead of enduring the
                   overhead of getElementById every time the handler runs,
                   querying the DOM is slow.
                */
                textField = document.getElementById("textField"),
            
                /* Instead of using new Array(), use an array literal. Literals are
                   shorter and behave in a more predictable way than the Array
                   constructor. Another benefit to using a literal is that you can
                   create the array and initialize it's values in one step avoiding
                   the tedious quotes[0] = "..."; quotes[1] = "..."; pattern of the
                   original code. Also, if you want to reorder the items in the list
                   you don't have to renumber them too.
                */
                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.",
                  // The last item in the list should not have a comma after it, some
                  // browsers will ignore it but others will throw an error.
                  "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;
                  }
            
                  textField.value = quotes[nextQuote];       
              }
            
              document.getElementById('button').addEventListener("click", buttonClickHandler, false);
            }(document)); /* This is the end of the self-invoking function. The document
                             object is being passed in as an argument. It will be imported
                             into the self-invoking function as a local variable also named
                             document. There are a couple of reasons to do this. Having it
                             aliased as a local variable will make any references to it
                             quicker since the browser will not have to look any further
                             up the scope-chain. Also, if this code is minified, the local
                             variable will be renamed to a shorter (often 1 character long)
                             name, saving download time, where references to the built-in
                             global document object would not.
                           */
            
            </script>
            

            包装代码的self-invoking function是现代JavaScript中非常常见的模式,熟悉它会很好。

            使用strict mode 将帮助您避免许多容易产生的错误。

            如果您将 JavaScript 代码部署到野外,您应该是 minifying 它。拥有一个构建过程可以通过为您自动化来简化它。我会推荐Grunt,它有很多预先构建的任务,可以让缩小和其他常见的构建任务变得容易。一开始设置起来可能有点棘手,但有很多很棒的文章可以让它更容易理解。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2022-01-19
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-05-05
              • 1970-01-01
              相关资源
              最近更新 更多