为什么这个javascript函数停止工作?

时间:2016-08-02 19:45:00

标签: javascript html css

我这里有一个简单的比较应用程序,它需要2个数字,看哪一个更大,然后相应地更改段落的内部HTML。当我运行它似乎工作正常,但是当我开始在第3或第4次插入新数字时,它停止工作并开始说较低的数字更高。这种情况似乎是随机的。任何人都可以向我解释为什么会发生这种情况吗?

HTML

<p>Enter 2 numbers to see which one is highest.</p>
<input type="text" id="firstnumber" class="inputs" class="clearme"/>
<input type="text" id="secondnumber" class="inputs"/>
<input type="button" class="inputs" value="submit" id="button"/>
<p id ="message" style="color: blue;">Answer appears here.</p>

CSS

.inputs {
  float : left;
}

#secondnumber {
  clear: both;
}

#button {
  clear: left;
}

p {
  clear: both;
}

的JavaScript

function myfunction(num1, num2) {
  if (num1 > num2) {
    document.getElementById("message").innerHTML = "The Higher number is " + num1 + ", which was the first value.";
  } else {
    document.getElementById("message").innerHTML = "The Higher number is " + num2 + ", which was the second value.";
  }
}

document.getElementById('button').onclick = function(){
  var x = document.getElementById("firstnumber").value;
  var y = document.getElementById("secondnumber").value;
  myfunction(x, y);
  console.log(x);
  console.log(y);
}

JSFiddle

非常感谢。

3 个答案:

答案 0 :(得分:4)

在比较数字之前,您需要转换数字。您可以使用Number()功能或unary plus

来完成此操作
PythonShell.run

<强> JSFiddle

if (Number(num1) > Number(num2)) {
  //...
};

<强> JSFiddle

答案 1 :(得分:2)

需要将字符串转换为数字。

  • Number(Str)
  • parseInt(Str, 10)
  • +Str

几乎没有办法:

&#13;
&#13;
function myfunction(num1, num2) {
  if (num1 > num2) {
    document.getElementById("message").innerHTML = "The Higher number is " + num1 + ", which was the first value.";
  } else {
    document.getElementById("message").innerHTML = "The Higher number is " + num2 + ", which was the second value.";
  }
}

document.getElementById('button').onclick = function() {
  var x = Number(document.getElementById("firstnumber").value);
  var y = Number(document.getElementById("secondnumber").value);
  myfunction(x, y);
  console.log(x);
  console.log(y);
}
&#13;
.inputs {
  float: left;
}
#secondnumber {
  clear: both;
}
#button {
  clear: left;
}
p {
  clear: both;
}
&#13;
<p>
  Enter 2 numbers to see which one is highest.
</p>
<input type="text" id="firstnumber" class="inputs" class="clearme" />
<input type="text" id="secondnumber" class="inputs" />
<input type="button" class="inputs" value="submit" id="button" />
<p id="message" style="color: blue;">
  Answer appears here.
</p>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您输入的值将作为字符串进行比较。

因此,像“10”这样的数字将显得小于“2”,因为它们是按字典顺序而不是数字地进行比较。您可以通过在比较它们时为num1和num2参数添加+来解决此问题

if (+num1 > +num2)