javascript switch()提供默认值?

问题描述 投票:-2回答:1

为什么此代码只给我默认值

<!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')。value更改为18,当我这样做时,它的输出为啤酒!但现在它只给了我期待。...

javascript html input switch-statement
1个回答
1
投票

您没有调用函数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>
© www.soinside.com 2019 - 2024. All rights reserved.