2015-07-24 1 views
0

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

<body> 
 
\t <script type="text/javascript"> 
 
\t var word = ["Getting lazy", "Shannon", "Letogasm", "fleek"]; 
 
\t var explanation = ["Getting lazy is the act of just laying on the ground after being 
 
\t \t \t slammed or a hard fall.Most commonly used amongst skaters, bmx riders, and other extreme 
 
\t \t \t sports. 
 
\t \t \t ", " 
 
\t \t \t The coolest person in the world. 
 
\t \t \t ", " 
 
\t \t \t Word used by Echelon and any other 
 
\t \t \t Jared Leto fan to describe the feeling of(sexual) pleasure/happiness associated with 
 
\t \t \t watching a Jared Leto/30 Second to Mars Music Video or Movie.In other words, a Jared Leto 
 
\t \t \t induced Orgasm. 
 
\t \t \t ", " 
 
\t \t \t on point "]; 
 

 
\t \t \t function inc() { 
 
\t \t \t \t var i = i++; 
 
\t \t \t \t return i; 
 
\t \t \t } 
 

 
\t \t \t function dec() { 
 
\t \t \t \t var i = i++; 
 
\t \t \t \t return i; 
 
\t \t \t } 
 
\t \t \t var decos = document.getElementById('deco'); 
 
\t \t \t decos.addEventListener('click', inc); 
 
\t \t \t var incos = document.getElementById('inco'); 
 
\t \t \t incos.addEventListener('click', dec); 
 
\t \t \t document.getElementById('the-h').innerHTML = 'word[i]'; 
 
\t \t \t document.getElementById('the-p').innerHTML = 'explanation[i]'; 
 
\t </script> 
 
\t <h1 id="the-h"></h1> 
 
\t <p id="the-p"></p> 
 
\t <input type="button" id="deco"><input type="button" id="inco"> 
 
</body>

ответ

0

ли эта работа? http://jsfiddle.net/pczxceju/5/

<body> 
<h1 id="the-h"></h1> 
<p id="the-p"></p> 
<input type="button" id="deco"><input type="button" id="inco"> 

<script type="text/javascript"> 
var word = ["Getting lazy", "Shannon", "Letogasm", "fleek"]; 
var explanation = ["Getting lazy is the act of just laying on the ground after being slammed or a hard fall. Most commonly used amongst skaters, bmx riders, and other extreme sports.", "The coolest person in the world. ", "Word used by Echelon and any other Jared Leto fan to describe the feeling of (sexual) pleasure/happiness associated with watching a Jared Leto/30 Second to Mars Music Video or Movie. In other words, a Jared Leto induced Orgasm.", "on point "]; 

var i=0; 

function updateDiv(id, content) { 
    document.getElementById(id).innerHTML = content; 
} 

function counter (step){ 
     if (word[i+step] !== undefined) { 
      i+=step; 
     } else { 
      step < 0 ? i=word.length-1 : i=0; 
     } 
     updateDiv('the-h',word[i]); 
     updateDiv('the-p',explanation[i]); 
} 

updateDiv('the-h',word[i]); 
updateDiv('the-p',explanation[i]); 

var decos = document.getElementById('deco'); 
decos.addEventListener('click', function() { 
    counter(-1); 
}, false); 
var incos = document.getElementById('inco'); 
incos.addEventListener('click', function() { 
    counter(+1); 
}, false); 

</script> 

</body> 
+0

Не работает, когда вы нажимаете кнопку '-' в первый раз или продолжаете нажимать кнопку' + ' – Tushar

+0

Я изменил код. Теперь это работает, не так ли? – verjas

+0

Пс. Я изменил код, чтобы сделать его более чистым. – verjas

2

Есть много ошибок в коде. См. Код ниже.

  1. Перемещение <script> в нижней части <body> или использовать DOMContentLoaded, чтобы проверить, если DOM готов к манипуляциям.
  2. Чтобы присвоить новое значение innerHTML из массива, не используйте кавычки вокруг него. Это присвоит строку innerHTML вместо фактического значения из массива.
  3. Строки должны быть заполнены в одной строке, строки в массиве explanation не заполняются на одной строке. Это синтаксическая ошибка. Или вы можете использовать \ в конце каждой строки для многострочных строк.
  4. Функции обработчика событий inc() и dec() фактически не обновляют DOM, они просто обновляют переменную в коде. Таким образом, пользователь не видит различий на экране.

Demo

var word = ["Getting lazy", "Shannon", "Letogasm", "fleek"]; 
 
var explanation = ["Getting lazy is the act of just laying on the ground after being slammed or a hard fall.Most commonly used amongst skaters, bmx riders, and other extreme sports. ", " The coolest person in the world.", "Word used by Echelon and any other Jared Leto fan to describe the feeling of(sexual) pleasure/happiness associated with watching a Jared Leto/30 Second to Mars Music Video or Movie.In other words, a Jared Leto induced Orgasm. ", "on point "]; 
 

 
var i = 0; 
 

 
var wordLen = word.length - 1; 
 

 

 
function updateHtml() { 
 
    console.log(i); 
 
    document.getElementById('the-h').innerHTML = word[i]; 
 
    document.getElementById('the-p').innerHTML = explanation[i]; 
 
} 
 

 
function inc() { 
 
    console.log(i); 
 
    i = (i + 1) > wordLen ? 0 : ++i; 
 
    updateHtml(); 
 
} 
 

 
function dec() { 
 
    i = (i - 1) < 0 ? wordLen : --i; 
 
    updateHtml(); 
 
} 
 

 
document.getElementById('deco').addEventListener('click', dec); 
 
document.getElementById('inco').addEventListener('click', inc);
<h1 id="the-h"></h1> 
 
<p id="the-p"></p> 
 
<input type="button" id="deco" value="-" /> 
 
<input type="button" id="inco" value="+" />

+0

Как это исправить? –

+0

Не работает. undefined –

+0

@ArielHalilajAl Проверить обновленный ответ – Tushar