“如果”条件不起作用。我该如何比较它们两者。我也尝试将值转换为整数类型,但仍然无法正常工作

时间:2018-09-08 07:28:04

标签: javascript if-statement

var v= document.getElementById('btn');

v.addEventListener('click', action);

var selection = document.getElementById('inputGroupSelect01');

function action(e) { 
  document.getElementById('inputGroupSelect01');
  console.log(selection.value);
  var b = parseInt("selection.value");
  console.log(typeof(b));
  if (b === 2) {
    console.log("congo number is 1");
  } 
  else { 
    console.log('not');
  }
}

3 个答案:

答案 0 :(得分:1)

此行是错误的:

var b = parseInt("selection.value");

您正在尝试将文字字符串"selection value"解析为整数,而不是解析value所引用字段selection的值。

应该是:

var b = parseInt(selection.value);

答案 1 :(得分:0)

问题似乎出在此行option上,它将给出一个未定义的

用该变量var b = parseInt("selection.value");替换该行

答案 2 :(得分:0)

b = parseInt(selection.value,10)更改为var b = parseInt("selection.value"); 由于您要解析的是字符串值,但字符串也应为整数,因此parseInt('1')将起作用,而parseInt('demo')将不起作用。因此您正在像这样var b = parseInt(selection.value);那样行不通。