Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   Перебор массива кнопкой (https://javascript.ru/forum/dom-window/52871-perebor-massiva-knopkojj.html)

Giyas 12.01.2015 21:33

Спасибо за подсказку. Вобщем обошелся без document.write. Получился такой код:
<input id="output" type="text">
<input type="button" value="Следующий" onclick="schet()"> 
<script language="JavaScript">
a = new Array(4);
a[0] = 'Зима';
a[1] = 'весна';
a[2] = 'лето';
a[3] = 'осень';
i = Math.round((Math.random()*3))
b=document.querySelector("input")
b.value = a[i]
function schet(){
  document.getElementById('output').value = a[i];
    if(i==a.length-1) i=-1
    this.value = a[++i];
}
</script>

В итоге все работает, но когда вставляю код на сайт, то кнопка работает, а рандом нет( Почему так?

Giyas 12.01.2015 21:52

Получилось! Исправил
b=document.querySelector("input")
на
b=document.getElementById('output')
Всем спасибо!)

Giyas 28.01.2015 22:07

Друзья! Снова вопрос. Поставил код на сайт. При обновлении страницы рандом работает как надо. А вот кнопка следующий после загрузки страницы при первом нажатии не срабатывает. Вот код:
<div id="div_1"></div>
<input type="button" value=">>>" onclick="schet()"style="margin: 5px 0px 0px 0px;"> 
<script language="JavaScript">
a = new Array(8);

a[0] = 'Первый';
a[1] = 'Второй';
a[2] = 'Третий';
a[3] = 'Четвертый';
a[4] = 'Пятый';
a[5] = 'Шестой';
a[6] = 'Седьмой';
a[7] = 'Восьмой';

i = Math.round((Math.random()*7))
b=document.getElementById('div_1')
b.innerHTML=a[i];
function schet(){
  b=document.getElementById('div_1')
	b.innerHTML=a[i];
    if(i==a.length-1) i=-1
    this.value = a[++i];
}
</script>

рони 28.01.2015 22:26

Giyas,
:cray:
<!DOCTYPE HTML>

<html>

<head>
  <title>Untitled</title>
  <meta charset="utf-8">
</head>

<body>
<div id="div_1"></div>
<input type="button" value=">>>" onclick="schet()"style="margin: 5px 0px 0px 0px;">
<script>
var a = [
        'Первый',
        'Второй',
        'Третий',
        'Четвертый',
        'Пятый',
        'Шестой',
        'Седьмой',
        'Восьмой'
    ],
    l = a.length,
    i = Math.ceil((Math.random() * l)),
    b = document.getElementById('div_1');
function schet() {
    b.innerHTML = a[++i % l];
};
schet()
</script>

</body>

</html>

Giyas 28.01.2015 23:00

рони,
Спасибо большое! Все получилось!)


Часовой пояс GMT +3, время: 20:52.