我组装了一个计算器,可以根据用户输入计算价格。它在一次输入时工作正常,但现在我必须在第二次用户输入时稍微缩放它。但这里有一个问题:用户可能不想在该字段中放置任何内容,因此它将是空的。这就是阻止我的代码的事情。我可以复制计算器函数并返回值,然后在第三个函数中将这两个值加在一起,但是当有一个空值时它不会工作。
只是为了它,一些简单的 HTML 代码:
//When I only calculate with this user input, its easy
<input type="text" id="rocktext"><br>
// But how to consider this and do the same exact calculations like with the
//first one and add those two result together?
<input type="text" id="rocktext2"><br>
最后的代码应该是这样的:
接受第一个用户输入,计算价格(如下面的代码)
IF(!!) 有第二个用户输入,计算价格并将其添加到 第一个
我是白痴用 JS 来尝试还是一开始就只是个白痴?
伙计们,希望收到你们的来信!
J.
初始JS代码如下:
function priceCalc() {
var inputs = document.getElementById("rocktext").value;
var length = inputs.length;
var accept = 6;
var initPrice = 8;
if (inputs<=accept){
// Since the code is much simpler right now i just put the result in HTML as follows:
document.getElementById("rockpricetotal").innerHTML = initPrice + " dollars";
//I can also return the the value calculated here like so:
//retVal = initPrice;
}
else {
var intLength = parseInt(length, 10);
var lengthGap = intLength - accept;
var totals = lengthGap * 0.8 + initPrice;
var prec = totals.toPrecision(3);
// Since the code is much simpler right now i just put the result in HTML as follows:
document.getElementById("rockpricetotal").innerHTML = prec + " dollars";
// Here also the return clause can be possible with the calculation result like so:
//retVal = prec;
}
// And the final return as an alternative to the innerHTML :
// return retVal;
}
最佳答案
为了使其可扩展,您可以向函数中可能存在的所有输入添加一个类(类似于 calcInput
),这样您就可以迭代所有这些输入,如果值不为空 (如果它是一个有效的数字),你把它放在计算中。
或者您可以只验证第二个输入是否为空,如果是,则调用 functionOne,如果不是,则调用 functionTwo:
function twoDifferentWays() {
var valueOne = document.querySelector("#rocktext").value;
var valueTwo = document.querySelector("#rocktext2").value;
if (!!valueTwo && !isNaN(valueTwo)) {
callsFunctionOne(valueOne, valueTwo);
} else {
callsFunctionTwo(valueOne, valueTwo);
}
}
关于html - 添加两个 javascript 函数(取决于输入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39213675/