将 onclick 事件添加到 blazor 中的 table,table 由 for 循环生成

Adding a onclick event to a table in blazor, with the table made by a for-loop

所以,我正在使用 blazor 来制作应用程序。在剃刀页面的 HTML 部分,我正在制作一个 table 像这样:

@for (int index = 1; index < amounts.Count; index++)
{
<table>
<tr>
    <td> @amounts[index] </td>
</tr>
</table>
}

我需要为每个单元格添加一个@onclick 事件,问题是该函数的参数随 for 循环而改变。

所以这意味着如果我这样做(见下文)。每个单元格都会执行 onclick(amounts.Count) (这是 table 的最后一个索引,索引的最后一个值)。

@for (int index = 1; index < amounts.Count; index++)
{
<table>
<tr>
    <td @onclick="()=>Redirect(index)"> @amounts[index] </td>
<tr>
</table>
}

我不确定我是否解释得足够多,我的问题是否清楚。如果不是,请告诉我。

一个解决方案可能是我获取单元格的行号。我已经尝试了一些东西,但如果你使用 for 函数创建这样的 table,我无法弄清楚如何获取行号。

你的问题是 index 的值在 lambda 中被“捕获”,当函数被调用时,Index 的值总是相同的。查找详细信息 here.

像这样更改您的代码:

@for (int index = 1; index < amounts.Count; index++)
{
   int localVal = index;
<table>
<tr>
    <td @onclick="()=>Redirect(localVal)"> @amounts[index] </td>
<tr>
</table>
}

当您在循环范围内引入变量时,编译器将知道为循环的每次迭代分别捕获该值。