Как размещали ответы уже говорилось, проблема вызвана тем, что 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, у него есть много готовых задач, чтобы упростить минимизацию и другие общие задачи сборки. Это может быть немного сложно настроить сначала, но есть много замечательных статей, которые могут сделать его намного легче понять.
Вы можете использовать комбинацию 'pop' и' push' бесконечно, чтобы вращать кавычки вместо поддержания счетчика. – elclanrs
Как вы называете 'buttonClickHandler'? Если вы вызываете его каждый раз, он всегда будет показывать вашу первую цитату, так как вы каждый раз инициализируете 'nextQuote'. – matthewpavkov
Как мне это сделать? – user3087780