繁体   English   中英

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

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

我试图从“ f2”减去“ f1”的值,它工作正常。 但是我只想要一次,但是当我单击“提交更多”按钮时,每次f2的值就从f2减小。 怎么可能只做一次。 当我放置值而不是从脚本调用它时,它会很好地工作。

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

请帮助

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

Math.abs(6-10) = 4;

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

如果您希望函数仅运行一次,则可以执行以下操作:

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

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

您的问题似乎在询问,无论单击提交按钮多少次,如何仅从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的值更改时再次起作用,只需在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