You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 5 表格每行调用JS函数渲染占位符HTML的实现问题

问题根因

你的代码核心问题是违反了HTML元素ID全局唯一的规范:你循环渲染表格每行的隐藏输入框、占位div都使用了相同的id属性,而jQuery全局选择器$('#xxx')永远只会匹配页面中第一个符合条件的元素,因此无法正确获取每行对应的数据、也无法将生成的内容插入到对应行的占位符中。


修改方案

1. 调整Razor视图代码

将原有固定的id属性替换为class属性,避免id重复冲突:

<td class="text-left">
   <input hidden type="hidden" asp-for="@clinic.RenewalDue" class="form-control renewal-due" />
   <input hidden asp-for="@clinic.VaccClinic.NextRenewalDueAt" class="form-control next-renewal-due" />
   <input hidden asp-for="@clinic.VaccClinic.DedesignationDate" class="form-control dedesignated-date" />

   <div class="designation-placeholder"></div>

   Training Status: <br /><br />
   Annual Returns Figures:
   @if (clinic.NumberOfVaccinations.HasValue)
   {
      <label>@clinic.NumberOfVaccinations.Value.ToString()</label>
      if (clinic.NumberOfAdverseEvents.HasValue)
      {
         <label> - @clinic.NumberOfAdverseEvents.Value.ToString()</label>
      }
      else
      {
        <label> - 0</label>
      }
   }
   else
   {
      <label style="background-color:red">
         Not Submitted
      </label>
   }
</td>

2. 调整jQuery遍历逻辑

遍历表格行时,限定选择器的查找范围为当前行内部,避免全局匹配:

// 提前存储全局配置的天数,避免循环内重复渲染
const numberOfDays = @(ViewBag.NumberOfDays ?? 90);

$('tr').each(function () {
    const $row = $(this);
    // 仅在当前行内查找对应元素
    const dedesignatedDate = $row.find('.dedesignated-date').val();
    const renewalDue = $row.find('.renewal-due').val();
    const nextRenewalDue = $row.find('.next-renewal-due').val();
    
    const statusHtml = DesignationStatus(dedesignatedDate, renewalDue, nextRenewalDue, numberOfDays);
    // 插入到当前行的占位符中
    $row.find('.designation-placeholder').html(statusHtml);
});

可选优化

如果你的表格包含表头行,建议给所有数据行添加统一的类名(比如data-row),遍历的时候使用$('tr.data-row').each(),避免处理表头行导致的取值异常。
原有DesignationStatus函数逻辑无需修改,可直接沿用。

内容的提问来源于stack exchange,提问作者KevBarri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 04:18:03