简体   繁体   English

如何与[if]一起使用[getElementById]?

[英]How to create a use [getElementById] with [if]?

I'm trying to make a projectile calculator, so it really need to change the way to calculate again & again until it is done. 我正在尝试制作射弹计算器,因此它确实需要更改一次又一次的计算方式,直到完成为止。

but now i'm facing with a problem: 但现在我面临一个问题:

var Height = Number(document.getElementById("Height").value);
var Velocity = Number(document.getElementById("Velocity").value);
var Range = Number(document.getElementById("Range").value);
document.getElementById("First").innerHTML = ((((Math.SQRT2 * Velocity) +     (Math.sqrt(19.6) * Velocity * Height)) * Math.cos(0.785398163)) / 9.8);
if (First < Range) 
    document.getElementById("show").innerHTML = "Need more velocity to success on this range";

This is my big problem >> on if (First < Range) << it won't work how many times I try it 这是我的大问题>> if (First < Range) <<在我尝试了几次后将无法正常工作

Seems like the if only work with var object, but i cant create a var object with these much complex calculation. 似乎是if只与工作var的对象,但我不能创建一个var与这些比较复杂的计算对象。 This make me can't continue to next calculation. 这使我无法继续进行下一个计算。

Problem : 问题

  • You have not declared the variable First . 您尚未声明变量First So it is undefined. 因此它是未定义的。 If you need to compare two variables, you first need to assign values to them. 如果需要比较两个变量,则首先需要为其分配值。 And for that you need to declare them first. 为此,您需要先声明它们。

Solution : 解决方案

Change this code: 更改此代码:

document.getElementById("First").innerHTML  = ...

to this: 对此:

var First = ((((Math.SQRT2 * Velocity) + ......
document.getElementById("First").innerHTML = First;

Then you can safely compare the two values: 然后,您可以安全地比较两个值:

if (First < Range)
    ....

Save your calculation to a variable, then you can refer to it in the rest of the script: 将计算结果保存到变量,然后可以在脚本的其余部分中引用它:

var FIRST = ((((Math.SQRT2 * Velocity) + (Math.sqrt(19.6) * Velocity * Height)) * Math.cos(0.785398163)) / 9.8);

document.getElementById("First").innerHTML = FIRST;

if (First < Range) { etc...

Try this 尝试这个

HTML HTML

<div id="Height">100</div>
<div id="Velocity">25</div>
<div id="Range">2</div>
<div id="First"></div>
<div id="show"></div>

Javascript: 使用Javascript:

var Height = Number(document.getElementById("Height").innerHTML);
var Velocity = Number(document.getElementById("Velocity").innerHTML);
var Range = Number(document.getElementById("Range").innerHTML);
document.getElementById("First").innerHTML = ((((Math.SQRT2 * Velocity) +     (Math.sqrt(19.6) *    Velocity * Height)) * Math.cos(0.785398163)) / 9.8);
var First=Number(document.getElementById("First").innerHTML);
if(First < Range)
document.getElementById("show").innerHTML = "Need more velocity to success on this range";

Fiddle: 小提琴:

Fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM