Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/445.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 每次单击按钮时更改文本_Javascript_Arrays_Button_Text - Fatal编程技术网

Javascript 每次单击按钮时更改文本

Javascript 每次单击按钮时更改文本,javascript,arrays,button,text,Javascript,Arrays,Button,Text,我找了很多,但找不到答案 我有一个报价列表,每次我点击按钮,我希望它转到一个新的报价。 有人能解释一下这里出了什么问题,我该怎么解决吗 <script language="Javascript"> function buttonClickHandler() { var textField = document.getElementById("textField"); var quotes = new Array();

我找了很多,但找不到答案

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

<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>
我用于数组的代码几乎相同,但每次单击都不会更改文本。我需要为阵列做些特殊的事情吗?帮助
因为每次调用函数nextQuote时都会将其重新设置为0

因为您在处理程序中声明了数组和索引,所以每次单击都会在索引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];
}

每次调用处理程序时,都将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];
}
var quotes=new Array();
quotes[0]=“别那么谦虚,你没那么伟大。”;
引用[1]=“道德上的愤怒是带着光环的嫉妒。”;
引语[2]=“荣耀是转瞬即逝的,而默默无闻是永恒的。”;
引用[3]=“世界上麻烦的根本原因是愚蠢的人自信,而聪明的人充满怀疑。”;
quotes[4]=“胜利属于犯下下下一个最后一个错误的玩家。”;
引用[5]=“他的无知是百科全书式的”;
引用[6]=“如果一个人尽力而为,还有什么?”;
引用[7]=“政治正确就是有礼貌的暴政。”;
引用[8]=“你可以逃避现实,但你无法避免逃避现实的后果。”;
引用[9]=“当一个人患有妄想症时,它被称为精神错乱;当许多人患有妄想症时,它被称为宗教。”;
var nextQuote=0;
var textField=document.getElementById(“textField”);
函数按钮ClickHandler(){
if(nextQuote<9){
nextQuote++;
}否则{
nextQuote=0;
}
textField.value=quotes[nextQuote];
}
试试下面的方法

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

而不是您的:

var nextQuote=0


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

不同之处在于工作的代码从ButtonChickHandler外部获取要递增的值

var currentValue=parseInt(textField.value)

当您每次调用buttonClickHandler时重新初始化它时

var nextQuote=0

我想如果你用一个新的名字来代替这个声明,它会起作用的

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

如前所述,问题的原因是
nextQuote
是在
buttonClickHandler
中定义的,因此每次函数完成执行时都会被销毁,每次函数开始时都会被重新创建并初始化为
0

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

标签的
早就被弃用了。不要用它。但是,它被
类型
属性替换。只要一个简单的
标记就可以在所有浏览器中使用,它们都默认为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>

(函数(文档){//使用一个自调用函数来保存变量
//在全球范围之外
“使用严格”;//强制浏览器进入严格模式
var nextQuote=0,//而不是使用单独的var语句
//包含所有变量声明的逗号
//在一份声明中。
/*由于我们将大量使用textField DOM元素,所以让我们缓存一个
将变量复制到处理程序之外,而不是将
每次处理程序运行时getElementById的开销,
查询DOM很慢。
*/
textField=document.getElementById(“textField”),
/*不要使用新数组(),而是使用数组文字
比数组更短,并且行为更可预测
使用文本的另一个好处是
一步创建数组并初始化其值
的冗长引号[0]=“…”;引号[1]=“…”模式
原始代码。另外,如果您想对列表中的项目重新排序
你不必把它们重新编号。
*/
引号=[
“别那么谦虚,你没那么伟大。”,
“道德上的愤怒是带着光环的嫉妒。”,
“荣耀转瞬即逝,而默默无闻是永恒的。”,
“世界上麻烦的根本原因是愚蠢的人自信,而聪明的人充满怀疑。”,
“胜利属于犯下最后一个错误的球员。”,
“他的无知是百科全书式的”,
“如果一个人尽了最大的努力,还有什么?”,
“政治正确就是有礼貌的暴政。”,
“你可以逃避现实,但你无法避免逃避现实的后果。”,
//列表中的最后一项后面不应该有逗号,有些
//浏览器会忽略它,但其他浏览器会抛出错误。
“当一个人患有妄想症时,它被称为精神错乱;当许多人患有妄想症时,它被称为宗教。”
];
函数按钮ClickHandler(){
nextQuote++;
//如果我们到达终点,请回滚到0
if(nextQuote>=quotes.length){
nextQuote=0;
}
textField.value=quotes[nextQuote];
}
document.getElementById('button')。addEventListener(“单击”,buttonClickHandler,false);
}(文件));/*这是自调用函数的结束。文件
对象正在作为参数传入。它将被进口
作为局部变量(也称为
<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>