Blazor onclick事件从循环传入计数器 [英] Blazor onclick event passing in counter from loop
问题描述
我目前正在通过Blazor的自行开发的解决方案来实现表格分页,并且遇到了一些困难。麻烦的代码如下(用于在网格下方呈现分页按钮):
I'm currently implementing table paging via a home grown solution in Blazor and coming across some difficulty. The troublesome piece of code is below (this is for rendering the paging buttons below a grid):
@for (int i = 0; i < vm.TotalPages; i++)
{
<button id="pg-button-@i" class="btn btn-primary btn-sm" type="button" onclick="@(() => GetTablePage(i))">@i</button>
}
在onclick事件中注意,我正在调用一个函数并传入 i
,表示当前循环的计数器。
Notice in the onclick event, I am calling a function and passing in i
, the counter for the current interation of the loop.
GetTablePage
方法如下:
protected async Task GetTablePage(int page)
{
Console.WriteLine("page number: " + page);
}
我的问题是,每个按钮都会使用 i
设置为 vm.TotalPages
的长度。
My issue is that EVERY button will call this function with i
set as the length of vm.TotalPages
.
这里是一个示例为了使这一点更加清楚:
Here is an example to try to make this more clear:
查看标记(注意,每个按钮的 id
均已适当设置):
View Markup (notice the id
of each button is set appropriately):
<button id="pg-button-0" class="btn btn-primary btn-sm" type="button">0</button>
<button id="pg-button-1" class="btn btn-primary btn-sm" type="button">1</button>
<button id="pg-button-2" class="btn btn-primary btn-sm" type="button">2</button>
<button id="pg-button-3" class="btn btn-primary btn-sm" type="button">3</button>
<button id="pg-button-4" class="btn btn-primary btn-sm" type="button">4</button>
<button id="pg-button-5" class="btn btn-primary btn-sm" type="button">5</button>
<button id="pg-button-6" class="btn btn-primary btn-sm" type="button">6</button>
在单击这些按钮中的任何一个时,我的 GetTablePage
函数正在将 7
写入控制台,这是 vm.TotalPages
集合的长度。
Upon clicking ANY of these buttons, my GetTablePage
function is writing 7
to the console which is the length of the vm.TotalPages
collection.
为什么会这样,我该如何克服?
Why is this happening and how can I overcome it?
推荐答案
因为 i
是一个变量,当您单击时,for循环总是结束,那一刻是7
Because i
is a variable and the for loop is always finished when you click, it is 7 on that moment
@for (int i = 0; i < vm.TotalPages; i++)
{
var tempint = i;
<button id="pg-button-@i" class="btn btn-primary btn-sm" type="button" onclick="@(() => GetTablePage(tempint))">@i</button>
}
这篇关于Blazor onclick事件从循环传入计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!