簡體   English   中英

如何在不使用全局變量的情況下將局部變量鏈接到其他函數?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM