为什么我的JS功能无法正常工作?

时间:2015-02-06 22:25:52

标签: javascript

我对Javascript很新,所以请原谅我缺乏知识。 我试图使用Javascript来找到两个数据点(x1,y1)(x2,y2)的斜率。斜率的等式是m = y1-y2 / x2-x1。这是我迄今为止在JS小提琴中所做的:http://jsfiddle.net/1wvfz0ku/ 问题是,当我尝试计算点数时,只会出现NaN。 就像我说我在JS中编码非常新,所以我无法看到我搞砸了。我们非常感谢任何帮助! : - )

<!DOCTYPE html>
<html>
<body>
<div style="width:250px;height:auto;margin:auto;">
<h1>Find the Slope of Two Data Points</h1>
<p>
Find the slope of two sets of points:
</p>
<var>M</var>=<p id="slope"></p>
Enter your points below:
<form id="points">
X<sub>1</sub>: <input type="text" id="x1"/><br/>
X<sub>2</sub>: <input type="text" id="x2"/><br/>
Y<sub>1</sub>: <input type="text" id="y1"/><br/>
Y<sub>2</sub>: <input type="text" id="y2"/><br/>
</form>
<script>
function findSlope() {
//The points//
var xOne = document.getElementById("x1").value;
var xTwo = document.getElementById("x2").value;
var yOne = document.getElementById("y1").value;
var yTwo = document.getElementById("y2").value;

//slope equation//
var op1 = yTwo - yOne;
var op2 = xTwo - xOne;
var answer = op1 / op2;
document.getElementById("slope").innerHTML = answer;
} 
function reset(){
document.getElementById("points","slope").reset();
}
</script>

<button type="submit" onClick="findSlope()">Find the Slope</button>
<button type="submit" onClick="reset()">Clear Points</button>
</div>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

works just fine ,除非 xTwo - xTwo0,在这种情况下,您尝试将数字除以0,在JavaScript中定义为NaN


那就是说:元素的value属性总是一个字符串。您刚刚使用过的所有操作(-/)都会隐式地从字符串转换为数字,但如果您使用+,则会发生#&#;} 39; d确实得到了一些非常奇怪的结果(因为带有字符串的+是连接而不是加法)。最好使用parseInt(theString, 10)明确确保您处理数字(如果您正在处理小数)。


允许xTwo - xOne0并将输入解析为十进制的示例:

&#13;
&#13;
function findSlope() {
  //The points//
  var xOne = parseInt(document.getElementById("x1").value, 10);
  var xTwo = parseInt(document.getElementById("x2").value, 10);
  var yOne = parseInt(document.getElementById("y1").value, 10);
  var yTwo = parseInt(document.getElementById("y2").value, 10);

  //slope equation//
  var op1 = yTwo - yOne;
  var op2 = xTwo - xOne;
  var answer = op2 === 0 ? "flat or whatever" : op1 / op2;
  document.getElementById("slope").innerHTML = answer;
} 

function reset(){
  document.getElementById("points","slope").reset();
}
&#13;
<div style="width:250px;height:auto;margin:auto;">
<h1>Find the Slope of Two Data Points</h1>
<p>
Find the slope of two sets of points:
</p>
<var>M</var>=<p id="slope"></p>
Enter your points below:
<form id="points">
X<sub>1</sub>: <input type="text" id="x1"/><br/>
X<sub>2</sub>: <input type="text" id="x2"/><br/>
Y<sub>1</sub>: <input type="text" id="y1"/><br/>
Y<sub>2</sub>: <input type="text" id="y2"/><br/>
</form>
<button type="submit" onClick="findSlope()">Find the Slope</button>
<button type="submit" onClick="reset()">Clear Points</button>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

http://www.w3schools.com/jsref/jsref_number.asp使用代码x = Number(x)并为所有变量

执行此操作
相关问题