我正在尝试将事件目标值传递给另一个函数



我设置了两个事件,一个以英尺为单位,另一个以英寸为单位。我试图获取每个事件的值,可以是英尺和英寸,但由于每个事件的范围,我做不到。有没有办法将这两个值都传递到我的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)

一个你正在尝试做的事情的例子。你还需要做更多的事情,例如我在下面使用了整数,但你可以使用浮点数,也许可以为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>

最新更新