2014-01-11 3 views
0

Я искал много, но не могу найти ответ ...текст изменения каждый раз кнопку нажал

У меня есть список цитат и каждый раз, когда я нажимаю кнопку, я хочу, чтобы пойти на новый цитаты. Может кто-нибудь объяснить, что здесь не так, и как я должен это исправить?

<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(); 

Код, который я использовал для моего массива, почти то же, но не меняет текст за клик. Есть ли что-то особенное для массивов? Помогите!!

+0

Вы можете использовать комбинацию 'pop' и' push' бесконечно, чтобы вращать кавычки вместо поддержания счетчика. – elclanrs

+1

Как вы называете 'buttonClickHandler'? Если вы вызываете его каждый раз, он всегда будет показывать вашу первую цитату, так как вы каждый раз инициализируете 'nextQuote'. – matthewpavkov

+0

Как мне это сделать? – user3087780

ответ

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]; 
} 
+0

благодарит за помощь! – user3087780

0

Потому что каждый раз, когда функция вызывается nextQuote повторно установлен в 0

0

вы assinging 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]; 
} 
+0

большое спасибо! – user3087780

0

попробовать что-то вроде

вар nextQuote = Math.floor ((Math.random() * 9) +1);

вместо своего:

вар nextQuote = 0;

позже измените размер 9 на размер массива и добавьте его после того, как вы указали все значения в свой массив.

0

Разница заключается в том, что код работает получает значение для увеличения снаружи buttonClickHandler

вар CurrentValue = ParseInt (textField.value);

, где, как вы повторно инициализировать его каждый раз buttonClickHandler называется

вар nextQuote = 0;

Я думаю, что это будет работать, если заменить эту декларацию с

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

Как размещали ответы уже говорилось, проблема вызвана тем, что nextQuote определяется внутри buttonClickHandler и, таким образом, разрушается каждый раз, когда функция заканчивает выполнение и воссоздается и инициализируется до 0 каждый раз, когда начинается функция.

Вы, кажется, изучаете JavaScript, используя очень старые учебники, следующий код покажет, как это можно перестроить в более современный стиль.

<script language="Javascript">language attribute тега <script> был устаревшим. Не используйте его. Он был заменен атрибутом type, однако don't use the type attribute either. Просто обычный тег <script> работает во всех браузерах, все они по умолчанию используют 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, у него есть много готовых задач, чтобы упростить минимизацию и другие общие задачи сборки. Это может быть немного сложно настроить сначала, но есть много замечательных статей, которые могут сделать его намного легче понять.

Смежные вопросы