向eventlistener添加多个元素



我有一个表单,有两个输入,将采取两个数字如下。并根据数学运算符显示每次计算的结果。我如何获得两个输入值并将其添加到eventListener以监视值的变化并根据每个数学运算符更新结果?

<div class="form">
<input class="input" id="firstNum" />
<input class="input" id="secondNum" />
</div>
<div class="grid">
<div class="grid-item">
<h3>Addition</h3>
<p id="addition"></p>
</div>
<div class="grid-item">
<h3>Substraction</h3>
<p id="substraction"></p>
</div>
<div class="grid-item">
<h3>Multiplication</h3>
<p id="multiplication"></p>
</div>
<div class="grid-item">
<h3>Division</h3>
<p id="division"></p>
</div>
</div>

operator.js导出每个数学运算符。

export function addition (a, b) { 
return parseInt(a) + parseInt(b)
}
export function substraction (a, b) { 
return parseInt(a) - parseInt(b)
}
export function multiplication (a, b) { 
return parseInt(a) * parseInt(b)
}
export function division (a, b) { 
return (a / b).toFixed(1)
}

script.js

import * as mathOperator from "./operators.js"
document.querySelectorAll(".input")
.forEach(function (element) { 
element.addEventListener("change", function (event) {
let a = event.currentTarget.getAttribute("id")
let b = event.currentTarget.getAttribute("id")
console.log(a, b)
document.getElementById("addition").textContent = mathOperator.addition(a, b)
document.getElementById("substraction").textContent = mathOperator.substraction(a, b)
document.getElementById("multiplication").textContent = mathOperator.multiplication(a, b)
document.getElementById("division").textContent = mathOperator.division(a, b)
})
})

只需使用id选择值并进行计算。

示例实现。

function addition(a, b) {
return parseInt(a) + parseInt(b)
}
function substraction(a, b) {
return parseInt(a) - parseInt(b)
}
function multiplication(a, b) {
return parseInt(a) * parseInt(b)
}
function division(a, b) {
return b === 0 ? 0 : (a / b).toFixed(1)
}
function calculate() {
const a = document.getElementById("firstNum").value || 0;
const b = document.getElementById("secondNum").value || 0;
document.getElementById("addition").textContent = addition(a, b)
document.getElementById("substraction").textContent = substraction(a, b)
document.getElementById("multiplication").textContent = multiplication(a, b)
document.getElementById("division").textContent = division(a, b)
}
document.querySelectorAll(".input")
.forEach(function (element) {
element.addEventListener("change", function (event) {
calculate()
})
})
<div class="form">
<input class="input" id="firstNum" />
<input class="input" id="secondNum" />
</div>
<div class="grid">
<div class="grid-item">
<h3>Addition</h3>
<p id="addition"></p>
</div>
<div class="grid-item">
<h3>Substraction</h3>
<p id="substraction"></p>
</div>
<div class="grid-item">
<h3>Multiplication</h3>
<p id="multiplication"></p>
</div>
<div class="grid-item">
<h3>Division</h3>
<p id="division"></p>
</div>
</div>

相关内容

  • 没有找到相关文章

最新更新