简体   繁体   English

如何在JavaScript中的数学函数中采用绝对值

[英]How to take absolute value in math function in javascript

I am trying to minus the value of "f1" from "f2" it works fine. 我试图从“ f2”减去“ f1”的值,它工作正常。 However i want it just once but when i click the submit more more button it reduces every time the value of f1 from f2. 但是我只想要一次,但是当我单击“提交更多”按钮时,每次f2的值就从f2减小。 How can it be done only once. 怎么可能只做一次。 It works well when i put value instead of when i call it from script. 当我放置值而不是从脚本调用它时,它会很好地工作。

    <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))
    }

pls help 请帮助

JavaScript中数学函数中的绝对值是Math.abs();。

Math.abs(6-10) = 4;

不确定确切要执行的操作,但要使用Math.abs()计算绝对值。

If you want the function to only work once, you can have something like this: 如果您希望函数仅运行一次,则可以执行以下操作:

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

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

Your question seems to be asking how to only subtract f1 from f2 only once, no matter how many times the submit button is clicked. 您的问题似乎在询问,无论单击提交按钮多少次,如何仅从f2中减去f1一次。 One way to do it would be to have a variable that tracks if the function has been called already, and don't do the calculation if it has. 一种实现方法是让一个变量跟踪该函数是否已被调用,如果已调用则不进行计算。 As for the title mentioning absolute value, this is called by Math.abs(value) 至于标题中提到的绝对值,这由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;
}

In order to get the function to be able to work again when the value of f1 changes, simply change the variable alreadyDone back to false when f1 changes 为了使函数能够在f1的值更改时再次起作用,只需在f1更改时将变量alreadyDone更改为false即可

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

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

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