我正在阅读有关回调函数的内容,这似乎很简单,但是我仍然不知道该怎么做。我想做什么。
我有一个表格,您在其中放置了体重和身高,并根据这些变量打印一些数量。但是,还有第三个变量,比如宽度,如果宽度小于50,我希望它打印此数量加上30。
我认为函数宽度是错误的,但是我无法解决。你能帮忙吗?
document.getElementById('submit').addEventListener('click', result);
function result() {
let weight = document.getElementById('weight').value;
let height = document.getElementById('height').value;
let width = document.getElementById('width').value;
document.getElementById('result').innerHTML = weightAndHeight(weight, height);
}
function weightAndHeight(weight, height) {
if (weight <= 50) {
if (height < 20) {
return '100';
} else if (height >= 20 && height < 100) {
return '200';
}
}
}
function width(width, weightAndHeight) {
if (width < 50) {
weightAndHeight += 30;
}
}
Weight: <input type="number" id="weight" /><br/> Height: <input type="number" id="height" /><br/> Widht: <input type="number" id="width" /><br/>
<button type="button" id="submit">Calculate</button>
<span id="result"></span>
答案 0 :(得分:0)
function result() {
let weight = document.getElementById('weight').value;
let height = document.getElementById('height').value;
let width = document.getElementById('width').value;
const weightAndHeight = weightAndHeight(weight, height);
document.getElementById('result').innerHTML = width(weight, weightAndHeight);
}
如果要付出更多努力,可以使用功能链接。在这种情况下,应使用所有必需的功能创建对象。每个函数应返回this
。最终您会得到类似的东西:
class SizeCalculator {
constructor() {
this.size = 0;
}
weightAndHeight(weight, height) {
.... // update this.size
return this;
}
width(width) {
.... // update this.size
return this;
}
length(length) {
.... // update this.size
return this;
}
}
let size = new SizeCalculator()
.weightAndHeight(weight, height)
.width(width)
.length(length)
.size;
更详细的信息如下: https://medium.com/backticks-tildes/understanding-method-chaining-in-javascript-647a9004bd4f-关于方法链接和回调的很好解释
答案 1 :(得分:0)
document.getElementById('submit').addEventListener('click', result);
function result() {
let weight = document.getElementById('weight').value;
let height = document.getElementById('height').value;
let width = document.getElementById('width').value;
document.getElementById('result').innerHTML = fnc2(width, fnc1(weight, height));
}
function fnc1(weight, height, width) {
if (weight <= 50) {
if (height < 20) return 100;
else if (height >= 20 && height < 100) return 200;
}else return 0;
}
function fnc2(width, val) {
if (width < 50) return val + 30;
return val;
}
Weight: <input type="number" id="weight" /><br/> Height: <input type="number" id="height" /><br/> Widht: <input type="number" id="width" /><br/>
<button type="button" id="submit">Calculate</button>
<span id="result"></span>