後台管理列表中,某欄位(如 Email、描述、備註)內容過長會撐破版面。需在前端自動截斷超長文字並顯示省略號,滑鼠懸停時可顯示完整內容(tooltip)。
$(document).ready(function() {
$("#Email tr").each(function() {
var $td = $(this).children("#Emailtd"); // 注意:id 應唯一,建議改用 class
var text = $td.text();
if (text.length > 46) {
$td.text(text.substring(0, 46) + "...")
.attr("title", text) // 滑鼠懸停顯示完整內容
.css("cursor", "help");
}
});
});
<tbody id="Email">
<c:forEach items="${Warns}" var="Warn">
<tr>
<td>${Warn.field1}</td>
<td>${Warn.field2}</td>
<td class="email-col">${Warn.mail}</td> <!-- 改用 class -->
<td>${Warn.field4}</td>
</tr>
</c:forEach>
</tbody>
原碼中 <td id="Emailtd"> 在迴圈內會產生重複 ID,違反 HTML 標準且導致 jQuery 選擇器僅匹配第一個。必須改用 class:
<td class="email-col">${Warn.mail}</td>
// jQuery 對應修改
$("#Email tr").each(function() {
var $td = $(this).find(".email-col");
// ...
});
現代瀏覽器支援純 CSS 截斷,效能更好、無閃爍、支援響應式:
.email-col {
max-width: 300px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: inline-block;
vertical-align: middle;
}
搭配 title 屬性或 Tooltip 元件即可達到同樣效果,零 JS 開銷。
.multi-line-ellipsis {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2; /* 顯示 2 行 */
overflow: hidden;
}
<style>
.email-col {
max-width: 280px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: inline-block;
vertical-align: middle;
}
</style>
<tbody id="Email">
<c:forEach items="${Warns}" var="Warn">
<tr>
<td>${Warn.field1}</td>
<td class="email-col" title="${Warn.mail}">${Warn.mail}</td>
<td>${Warn.field4}</td>
</tr>
</c:forEach>
</tbody>
// 僅需 JS 處理動態新增的行
function bindEmailEllipsis($container) {
$container.find(".email-col").each(function() {
var $this = $(this);
if (!$this.attr("title")) $this.attr("title", $this.text());
});
}
雖然 jQuery 字串截斷方案可行,但現代開發應優先採用 CSS text-overflow: ellipsis 方案,效能優、維護易、響應式友善。若確需 JS 處理(如動態渲染、多行鉗制不支援舊瀏覽器),請務必修正重複 ID 問題,改用 class 選擇器。