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

如何使用JSP为HTML表格行标签动态生成唯一ID?

给JSP生成的表格行添加唯一ID的解决方案

很简单,这里有两种靠谱的方法,看你需求选就行:

方法一:利用医院的唯一编号(推荐)

既然你的HospitalDTO里有number字段(从getNumber()获取),而且这个字段应该是业务上唯一的(不然也不会存成long类型),直接用它来做ID的一部分就好,还能让ID更有语义:

修改你现有代码里的<tr>标签部分,把ID直接拼进去:

<% 
ArrayList<HospitalDTO> list=(ArrayList<HospitalDTO>)request.getAttribute("arrayList"); 
for(HospitalDTO hsp:list) { 
    long no=hsp.getNumber(); 
    String name=hsp.getName(); 
    Date nextDD=hsp.getNextDD(); 
    Date lastDD=hsp.getLastDD(); 
    // 给<tr>添加唯一ID,用hospital-前缀+编号避免纯数字ID的问题
    out.println("<tr id='hospital-" + no + "'><td class='text-center' >"+no+"</td><td class='text-center'>"+name+"</td><td class='tex..."); 
}
%>

这样生成的行ID会是类似hospital-123、hospital-456这种,既唯一又能一眼看出对应的是哪个医院的行。

方法二:用循环索引兜底

如果担心number字段可能重复(虽然正常业务里不会),可以给循环加个计数器,用索引来生成唯一ID:

<% 
ArrayList<HospitalDTO> list=(ArrayList<HospitalDTO>)request.getAttribute("arrayList"); 
int rowCounter = 0; // 新增计数器
for(HospitalDTO hsp:list) { 
    rowCounter++;
    long no=hsp.getNumber(); 
    String name=hsp.getName(); 
    Date nextDD=hsp.getNextDD(); 
    Date lastDD=hsp.getLastDD(); 
    // 用行索引生成ID
    out.println("<tr id='hospital-row-" + rowCounter + "'><td class='text-center' >"+no+"</td><td class='text-center'>"+name+"</td><td class='tex..."); 
}
%>

这种方式生成的ID是hospital-row-1、hospital-row-2...也能保证唯一。

小提醒

HTML里的ID不能以纯数字开头,所以一定要加前缀(比如hospital-或者hospital-row-),不然会不符合规范哦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:06:47