【问题标题】:Adding a onclick event to a table in blazor, with the table made by a for-loop [duplicate]将 onclick 事件添加到 blazor 中的表格,表格由 for 循环 [重复]
【发布时间】:2021-05-25 15:56:50
【问题描述】:

所以,我正在使用 blazor 来制作应用程序。在剃须刀页面的 HTML 部分,我正在制作这样的表格:

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

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

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

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

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

一种解决方案可能是我获取单元格的行号。我已经尝试了一些方法,但是如果您使用 for 函数制作这样的表格,我无法弄清楚如何获取行号。

【问题讨论】:

    标签: c# html onclick blazor


    【解决方案1】:

    你的问题是 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>
    }
    

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

    【讨论】:

    • 太棒了,我知道错误是什么。但我不知道它这么容易修复。非常感谢!
    猜你喜欢
    • 2020-08-31
    • 1970-01-01
    • 2013-10-15
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    • 2013-03-29
    • 2015-06-20
    相关资源
    最近更新 更多