Javascript切换语句不起作用?

时间:2014-06-24 08:59:25

标签: javascript

function decinumber(y){
var x = document.getElementById("areafield").value;
  if (x == 0){  alert(x);
   switch(y){
   case "one": x = 1; break;
   case "two": x = 2; break;
   case "three": x = 3; break;
   case "four": x = 4; break;
   case "five": x = 5; break;
   case "six": x = 6; break;
   case "seven": x = 7; break;
   case "eight": x = 8; break;
   case "nine": x = 9; break;
   case "zero": x = 0; break;
    }
   }
 }

此函数中的变量y是一个id,该函数来自HTML中单击的按钮。 switch语句不可访问,因为当我将alert语句放在switch括号内时它不起作用,但是当它在if括号内时它起作用。

2 个答案:

答案 0 :(得分:0)

它运作良好这里是小提琴

Fiddle

function decinumber(y){
var x = 0;
if (x == 0){  alert(x);
switch(y){
case "one":{ x = 1;alert(1); break;}
case "two": x = 2; break;
case "three": x = 3; break;
case "four": x = 4; break;
case "five": x = 5; break;
case "six": x = 6; break;
case "seven": x = 7; break;
case "eight": x = 8; break;
case "nine": x = 9; break;
case "zero": x = 0; break;
 }
 }
 }

decinumber('one');

答案 1 :(得分:0)

我复制/粘贴你的代码和adapted it for jsfiddle...它对我有用: - )

您必须检查x变量,它应设置为0.您必须确保y值为===切换表达式: - )

编辑:之后添加一些代码 顺便说一句,我更喜欢这种语法,而不是Switch ... case一个

function decinumber(y) {
    var hash = {
        'zero'  : 0,
        'one'   : 1,
        'two'   : 2,
        'three' : 3,
        'four'  : 4,
        'five'  : 5,
        'six'   : 6,
        'seven' : 7,
        'eight' : 8,
        'nine'  : 9        
    }

    // carefull, I'am replacing the value of the x input value, instead of just putting x
    var x = document.getElementById("areafield");
    if (x.value == 0 || x.value == '') {
      x.value = hash[y.toLowerCase()];
    }
 }