[英]How do you link local variables to other functions without having to use global variables?
如何链接下面的 3 个函数,以便获得mathFormula
output 的答案?
HTML 文本:
<div id = "rowContainer"></div>
JavaScript 文字:
function mathFormula(x, y) {
return x * y;
}
const mainDiv = document.getElementById("rowContainer");
function newRow() {
const input1 = document.createElement("input");
mainDiv.appendChild(input1);
const input2 = document.createElement("input");
mainDiv.appendChild(input2);
const result = document.createElement("div");
mainDiv.appendChild(result);
}
mainDiv('keyup', function() {
const a = input1.value;
const b = input2.value;
const sum = mathFormula(a,b);
result.textContent = sum;
})
函数可以在包含 scope 的变量中看到变量,因此如果在 newRow function 中定义了 keyup 侦听器,它将捕获输入元素的上下文。
要注意的另一件事是,除非附加到特定行(在 scope 中捕获该行的输入),否则侦听器是模棱两可的。 下面的代码片段添加了一个额外的 div 来保存行,并在 row-div 级别附加侦听器。
const mainDiv = document.getElementById('maindiv'); function mathFormula(x, y) { return x * y; } function addRow() { const rowDiv = document.createElement("div"); mainDiv.appendChild(rowDiv); const input1 = document.createElement("input"); rowDiv.appendChild(input1); const input2 = document.createElement("input"); rowDiv.appendChild(input2); const result = document.createElement("div"); rowDiv.appendChild(result); rowDiv.addEventListener("keyup", event => { const a = input1.value; const b = input2.value; result.textContent = mathFormula(a, b); }) } addRow() addRow()
<div id="maindiv"> </div>
在这种情况下,我们只需要 2 个函数。 newRow()
和mathFormula
。 创建 3 个inputs
而不是一个 div。 一次将所有输入附加到我们的rowContainer
中,无需单独执行。 然后我正在点击我在 html 中创建的按钮。 所以,当我们点击按钮时。在里面我调用我们的mathFormula
并传递输入 1 和输入 2。
let multiply=mathFormula(input1,input2)
将这两个输入作为 object Still 发送给 mathFormula。然后将这些输入分配给 x,y。 然后我说x = x.value
& y =y.value
然后返回x*y
的单个值,该值存储在multiply
变量中。 因为我们说过。
let multiply=mathFormula(input1,input2)
将该值放入结果输入中。
我希望它对你有帮助。如果你有任何疑问,你可以问
const mainDiv = document.getElementById("rowContainer"); const btn = document.getElementById("btn"); function mathFormula(x, y) { x=x.value; y=y.value return x * y; } newRow(); /*-----Calling the newRow() rightAway*/ function newRow() { const input1 = document.createElement("input"); const input2 = document.createElement("input"); const result = document.createElement("input"); mainDiv.append(input1, input2, result); btn.addEventListener("click",()=>{ let multiply=mathFormula(input1,input2) result.value=multiply; }) }
<div id="rowContainer"></div> <button id="btn">Click</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.