[英]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.