[英]I'm trying to pass event target values to another function
I set up two events, one in feet and one in inches. 我设置了两个事件,一个英尺,一个英寸。 I'm trying to grab the value of each event which would be feet and inches but I can't because of each event's scope.
我试图获取每个事件的价值(英尺和英寸),但是由于每个事件的范围,我无法做到。 Is there a way to pass both values into my totalHeight function so that I can add the two values together?
有没有办法将两个值都传递到我的totalHeight函数中,以便可以将两个值加在一起?
const justFeet = totalFeet.addEventListener('input', (e) => { const heightInFeet = e.target.value; let displayFeet = document.createElement('h3') displayFeet.textContent = heightInFeet * 12 // totalInches.appendChild(displayFeet) }) const justInches = inches.addEventListener('input', (e) => { const addOnInches = e.target.value; let displayInches = document.createElement('h3') displayInches.textContent = addOnInches // totalInches.appendChild(displayInches) }) function totalHeight (feet, inches) { const finalTotal = feet + inches; let finalHeight = document.createElement('h3') finalHeight.textContent = finalTotal totalInches.appendChild(finalHeight) } totalHeight(displayFeet, displayInches)
An example of what it looks like you are trying to do. 您正在尝试做的事的一个示例。 There's more you need to do, for example I used integers below but you could use floating numbers and perhaps add better handling for isNaN().
您还需要做更多的事情,例如我在下面使用了整数,但是您可以使用浮点数,并且可能为isNaN()添加了更好的处理方法。
<html>
<style>
</style>
Feet:<input id="feet" type="number"></input>
Inches:<input id="inches" type="number"></input>
<h3>Feet converted to inches: <span id="displayFeetToInches"></span></h3>
<h3>Inches: <span id="displayInches"></span></h3>
<h3>Total inches:<span id="finalHeight"></span></h3>
<script>
const feet = document.getElementById("feet");
const inches = document.getElementById("inches");
const total = document.getElementById("total"); //in inches
const displayFeetToInches = document.getElementById("displayFeetToInches"); //in inches
const displayInches = document.getElementById("displayInches"); //in inches
const justFeet = feet.addEventListener('input', (e) => {
console.log('justFeet');
const heightInFeet = e.target.value;
displayFeetToInches.textContent = heightInFeet * 12;
totalHeight();
})
const justInches = inches.addEventListener('input', (e) => {
console.log('justInches');
const addOnInches = e.target.value;
displayInches.textContent = addOnInches
totalHeight();
})
function totalHeight (feet, inches) {
console.log('totalinches');
const ftToInches = displayFeetToInches.textContent;
const addOn = displayInches.textContent;
const finalTotal = parseInt(ftToInches) + parseInt(addOn);
finalHeight.textContent = finalTotal
}
</script>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.