javascript switch () дает значение по умолчанию? - PullRequest
0 голосов
/ 07 апреля 2020

почему этот код только дает мне значение по умолчанию

<!DOCTYPE html>
<html>
<body>
<p id= "demo"></p>
<input id="age" />
<button onclick="document.getElementById('demo').innerHTML=text">try it</button>

<script>
var text;
age = document.getElementById('age').value;
switch (age) {
  case 10:
    text = "diuble";
    break;
  case 13:
    text = "puberty";
    break;
  case 18:
    text = "Beer!";
    break;
  default:
    text = "Looking forward to the Weekend";
}
</script>
</body>
</html>

Я попытался изменить значение document.getElementById ('age'). На 18, когда я делаю это, это дает мне вывод как пиво ! но сейчас это только дает мне смотреть вперед ...

1 Ответ

1 голос
/ 07 апреля 2020

Вы не вызываете функцию onclick, а запускаете код при загрузке документа. Правильный способ сделать это будет:

function getText(){
          var text;
          age = document.getElementById('age').value;
          age = parseInt(age)
          switch (age) {
               case 10:
                    text = "diuble";
                    break;
               case 13:
                    text = "puberty";
                    break;
               case 18:
                    text = "Beer!";
                    break;
               default:
                    text = "Looking forward to the Weekend";
          }
          document.getElementById('demo').innerHTML=text
}
<p id= "demo"></p>
<input id="age" />
<button onclick="getText()">try it</button>
...