我在index.js中有一个函数,如下所示,它是从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传递(BtnID)的新按钮ID,如上面在index.js中所示。现在我想问一下问题是什么。谢谢。
Navbar.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);
}}
发布于 2022-09-09 06:53:49
您可以使用ElementReference将按钮元素传递给js函数。然后从元素引用中获取id属性。
Navbar.razor:
<div id="items">
<button @ref="_btn1Ref" id="0" @onclick=OpenDialog1>one</button>
<button @ref="_btn2Ref" id="1" @onclick=OpenDialog2>two</button>
</div>
@code{
private ElementReference _btn1Ref;
private ElementReference _btn2Ref;
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, _btn1Ref);
}
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, _btn2Ref);
}
}index.js:
window.getValues = function (val1, val2, elem) {
var BtnID = elem.getAttribute('id');
yAxis[BtnID].setExtremes(val1, val2);
}https://stackoverflow.com/questions/73654171
复制相似问题