表格欄位寬度有限,文字一長就被截斷。最簡單的補救方式是把 cell 的內容同步寫進 title,滑鼠停留時瀏覽器會自動彈出提示。幾行程式就能搞定。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>將table的每個td的內容自動賦值給其title屬性</title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<style type="text/css">
.tbStyle td{ border:1px solid #F00 }
.tbStyle th{ border:1px solid #F00 }
</style>
<script src="jquery-1.10.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
//table的最後一列不給其title賦值
var cellIndex = parseInt($(".tbStyle th").length) - 1;
$(".tbStyle tr td").each(function(){
if(this.cellIndex != cellIndex){
$(this).attr("title", $(this).text());
//alert($(this).parent().get(0).rowIndex); 輸出所在行
}
});
});
</script>
</head>
<body>
<table class="tbStyle">
<tr>
<th>第一列</th><th>第二列</th><th>第三列</th><th>第四列</th>
</tr>
<tr>
<td>aaaaaaa</td><td>bbbbbbb</td><td>ccccccc</td><td>ddddddd</td>
</tr>
<tr>
<td>eeeeeee</td><td>fffffff</td><td>ggggggg</td><td>hhhhhhh</td>
</tr>
<tr>
<td>iiiiiii</td><td>jjjjjjj</td><td>kkkkkkk</td><td>lllllll</td>
</tr>
</table>
</body>
</html>
this.cellIndex——取得該 td 在其所屬列中的索引,從 0 起算。用它就能精準跳過最後一欄。
$(this).text()——取 cell 的純文字內容。這裡用 text() 而非 html(),是因為 title 提示只需要可讀文字。
$(this).parent().get(0).rowIndex——往上取到 tr 再讀 rowIndex,可以知道這個 cell 位於第幾列,需要行列座標時用得上。
範例中先算出 th 的數量減一作為要排除的索引,通常是因為最後一欄放的是「操作」按鈕或已經是完整顯示的欄位,加上 title 只會造成多餘的提示框。
如果表格資料是後端動態產生的,這段初始化必須在資料填入「之後」執行,否則會掃到空表。純使用原生 JS 的等價寫法是 document.querySelectorAll('.tbStyle tr td') 搭配 forEach 與 setAttribute,不必依賴 jQuery。
另外,若 cell 內容本身很長,原生 title 的單行提示體驗其實有限,這種情況改用 CSS tooltip 或自訂彈出層會更好用。