簡體   English   中英

調用 JS function 的 .NET 方法

[英].NET method that invoke JS function

我在 index.js 中有一個 function,如下所示,它是從 navbar.razor 調用的

                    // gets the ID of button clicked - always gets the correct id
                    var BtnID = null 
                    var buttonElements = document.querySelectorAll('#items button');
                    for (var i = 0; i < buttonElements.length; i++) {
                        buttonElements[i].addEventListener('click', function () {                      
                            BtnID = this.getAttribute('id');
                        });
                    };
                    

                   // invoked from navbar.razor
                   // here is the problem, it works initially but does not work or set new ID when I switch from (page2-> page1-> page2). Remembers the old ID that was clicked before switching page.
                   window.getValues = function (val1, val2) {
                       yAxis[BtnID].setExtremes(val1, val2);                         
                 }

window.getValues 最初運行良好。 但是一旦我切換頁面,比如 page2 到 page1 並再次返回到 page2(這是應用此功能的地方),它只記住舊 ID,而不是單擊的新按鈕 ID,或者不接受新 ID 傳遞( BtnID)如上面 index.js 中所示。 請問我現在會有什么問題。 謝謝你。

導航欄.razor:

    <div id="items">
      <button id="0" @onclick=OpenDialog1>one</button>
      <button id="1" @onclick=OpenDialog2>two</button>
    </div>
                                  
    @code{
    private MyData model1 = new MyData { val1= 0, val2= 0 };
    private MyData model2 = new MyData { val1= 0, val2= 0 };
  
    private IModalDialog? modalDialog;

    private async Task OpenDialog1()
    {
        var request = new ModalRequest { InData = this.model1 };
        if (this.modalDialog is not null)
            await modalDialog.ShowAsync<MyForm>(request);      
        await JSRuntime.InvokeVoidAsync("getValues", this.model1.val1, this.model1.val2);
    }

    private async Task OpenDialog2()
    {
        var request = new ModalRequest { InData = this.model2};
        if (this.modalDialog is not null)
            await modalDialog.ShowAsync<MyForm>(request);      
        await JSRuntime.InvokeVoidAsync("getValues", this.model2.val1, this.model2.val2);
    }

}

您的getValues function 正在成為閉包。 閉包是一個 function,它從其內部 scope 引用外部 scope 中的變量。 閉合將外部 scope 保留在其內部 scope 內。

您應該將獲取按鈕 ID 的代碼放在 function 中:

window.getValues = function (val1, val2) {
    var BtnID = null; 
    var buttonElements = document.querySelectorAll('#items button');
    for (var i = 0; i < buttonElements.length; i++) {

        buttonElements[i].addEventListener('click', function () {                      
            BtnID = this.getAttribute('id');
        });
    };
  
    yAxis[BtnID].setExtremes(val1, val2);                         
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

暫無
暫無

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

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