簡體   English   中英

如何返回由 HTML 按鈕單擊調用的 JavaScript function 的值?

[英]How can I return a value of a JavaScript function, which is called by a HTML button click?

如果單擊按鈕,我想設置 var 索引。 但我也想在function2中使用var index。 有沒有辦法在不使用全局的情況下做到這一點(通過使用返回)?

HTML:

<button id="edit" onclick="editBox()">Bearbeiten</button>

JS:

function editBox() {
    var index = $(event.target).parent().attr("id");
}

function function2() {
    //some code...
}

你的意思是這樣的:

function editBox() {
    var index = $(event.target).parent().attr("id");
    function2(index);
}

function function2(r) {
    //some code ( r is id now)
}

If a variable is declared inside a function, its scope is limited to that function and there is no way to access its value from outside the function.

來自w3schools

局部變量有Function scope :它們只能從 function 內部訪問。

要訪問第二個 function 中的相同變量,必須在兩個函數之外使用var關鍵字聲明它。 例如:

var index;

function editBox() {
  index = $(event.target).parent().attr("id");
}

function function2() {
  console.log(index);
}

唯一的另一種可能性是將變量index作為參數傳遞給function2() ,但這僅在從editBox()內部調用function2()時才有效。

您應該首先從函數 scope 中定義一個變量,然后調用/分配它。

在這里,您有一個工作片段。

 let value; function func1(id) { value = id; console.log('clicked', id); } function func2() { alert(value); }
 <button id="btn" onclick="func1(this.id)"> Click me and get the id </button> <button id="btn2" onclick="func2()"> Call second function </button>

簡短回答: index需要存在於比編輯框 scope 大的 scope 中。

你不想要一個全局變量,所以你可以創建一個“閉包”。 在 Javascript 中,您可以使用 IFFE(立即調用 Function 表達式)來執行此操作。 這樣,許多函數和其他代碼段共享相同的 scope,但它仍然是“本地的”,而不是全局的。

 (function(){ var index; $('#edit').on('click', function editBox(event) { index = $(event.target).parent().attr("id"); }); function function2() { // some code console.log(index); } // Other code that can call function2 and use index variable... })();
 <button id="edit">Bearbeiten</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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