2013-03-25 19 views
1

我想从“f2”减去“f1”的值,它工作正常。不过,我只需要它一次,但是当我点击提交更多按钮时,它会减少每次f2的f1值。它如何只能做一次。当我把价值,而不是从脚本调用时,它运作良好。如何在JavaScript中取数学函数的绝对值

<form name=bills> 

<p><input type="text" name="f1" size="20"> 
<input type="text" name="f2" size="20" value="30"></p> 
    <input type="button" value="Submit" onclick="cbs(this.form)" name="B1"> 

    <Script> 
    function cbs(form) 

    { 
     form.f2.value = (([document.bills.f2.value] * 1) - (document.bills.f1.value * 1)) 
    } 

请帮助

回答

1

在JavaScript中的数学函数的absulute值为Math.abs();

Math.abs(6-10) = 4; 
1

不知道你想什么做的,但计算绝对值使用Math.abs()

0

如果你希望函数只能使用一次,你可以有这样的事情:

hasBeenRun = false; //have this variable outside the function 

if(!hasBeenRun) { 
    hasBeenRun = true; 
    //Run your code 
} 
0

你的问题好像是问如何只从F2减去F1只有一次,无论多少次提交按钮被点击。一种方法是创建一个跟踪函数是否已被调用的变量,如果已经调用,则不执行计算。至于标题提的绝对值,这是由Math.abs(value)

<Script> 
var alreadyDone = false; 
function cbs(form) 
{ 
    if (alreadyDone) return; 
    // this one takes the absolute value of each value and subtracts them 
    form.f2.value = (Math.abs(document.bills.f2.value) - Math.abs(document.bills.f1.value)); 

    // this one takes the absolute value of the result of subtracting the two 
    form.f2.value = (Math.abs(document.bills.f2.value - document.bills.f1.value)); 
    alreadyDone = true; 
} 

为了叫了功能,以便能够重新工作时的F1的值发生变化,只是改变变量alreadyDone回假F1变化时

<input type="text" name="f1" onChange="alreadyDone=false;" size="20"> 
+0

Thx john。正如你所说的那样工作。不过,我需要它不应该改变,但当F1的变化比它应该再次工作一次。 Thx再次约翰 – 2013-03-26 09:08:16

+0

@chandrabhushan,我编辑了我的答案,以显示如何在F1更改时再次使功能工作。 – jonhopkins 2013-03-26 12:27:09

相关问题