我在下面给出了一个公式:
weightdifference = (|crushedWeight - weightBA| / weightBA )* 100%
其中 weightBA 和 crushedWeight 是输入文本的值。我确实做了一个如下所述的功能:
function calDiffWeight() {
var weightDS = document.getElementById("weightDS");
var crushedWeight = document.getElementById("crushedWeight");
var abs = -1;
var diffWeight = ((crushedWeight - weightDS) * abs) / weightDS * 100;
document.getElementById("diffWeight").value = diffWeight;
}
并且|crushedWeight - weightBA|
中的绝对计算我应该怎么做?
答案 0 :(得分:1)
根据您的代码,我做了以下更改:
Math.abs()
将数字设为绝对数字。
const
form = document.getElementById('form');
form.addEventListener('submit', onFormSubmit);
function onFormSubmit() {
event.preventDefault();
calDiffWeight();
}
function calDiffWeight() {
var weightDS = parseFloat(document.getElementById("weightDS").value);
var crushedWeight = parseFloat(document.getElementById("crushedWeight").value);
var diffWeight = (Math.abs(crushedWeight - weightDS)) / weightDS * 100;
document.getElementById("diffWeight").value = diffWeight;
}
<form id="form">
<label>
WeightDS:
<input type="number" id="weightDS"/>
</label>
<label>
Crushed Weight:
<input type="number" id="crushedWeight"/>
</label>
<button>Calculate</button>
</form>
<p>Result</p>
<input type="number" id="diffWeight"/>
答案 1 :(得分:1)
如果weightDS
是输入框,我建议使用document.getElementById("weightDS").value;
,因为只需getElementById
即可获得dom节点。不是它可能包含的任何价值。
这里有一个更大更好的答案How do I get the value of text input field using JavaScript?
答案 2 :(得分:1)
方法document.getElementById();
返回HTML元素。显然你不能用HTML元素做数学。因此,您可以正确地查找该HTML元素的value
属性。因为它是一个字符串,所以将其解析为整数(或根据您的情况浮动)。
var weightDS = parseInt(document.getElementById("weightDS").value);
var crushedWeight = parseInt(document.getElementById(document.getElementById("crushedWeight").value);
答案 3 :(得分:0)
在document.getElementById(“weightDS”)
之后使用.valuefunction calDiffWeight() {
var weightDS = document.getElementById("weightDS").value;
var crushedWeight = document.getElementById("crushedWeight").value;
var abs = -1;
var diffWeight = ((crushedWeight - weightDS) * abs) / weightDS * 100;
document.getElementById("diffWeight").value = diffWeight;
}
答案 4 :(得分:0)
document.getElementById('elementId');
返回一个DOM元素。为了获得价值,您必须调用value
属性。
以下是您的示例的解决方案:
var weightDS = parseInt(document.getElementById("weightDS").value);
var crushedWeight = parseInt(document.getElementById(document.getElementById("crushedWeight").value);