點擊「待選擇球隊」表格中的任一行,該行會平滑移動至「選中的球隊」表格,並自動移除原位置。滑鼠懸停時高亮提示,游標變為手型,直觀體現可操作性。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery 球隊選擇互動</title>
<style>
.container { max-width: 600px; margin: 40px auto; font-family: sans-serif; }
h3 { color: #333; border-bottom: 2px solid #1976d2; padding-bottom: 8px; }
table { width: 100%; border-collapse: collapse; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
th, td { padding: 12px 16px; border: 1px solid #e0e0e0; text-align: left; }
th { background: #f5f5f5; font-weight: 600; }
#tableToSelect tbody tr { cursor: pointer; transition: background 0.2s; }
#tableToSelect tbody tr:hover { background: #fff3e0; }
#tableSelected tbody tr { background: #e8f5e9; }
.empty-hint { color: #999; font-style: italic; text-align: center; padding: 20px; }
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container">
<h3>待選擇球隊 (點擊行選擇)</h3>
<table id="tableToSelect">
<thead><tr><th>球隊</th><th>得分</th></tr></thead>
<tbody>
<tr><td>火箭</td><td>100分</td></tr>
<tr><td>奇才</td><td>99分</td></tr>
<tr><td>小牛</td><td>98分</td></tr>
<tr><td>湖人</td><td>97分</td></tr>
<tr><td>勇士</td><td>96分</td></tr>
</tbody>
</table>
<h3>已選球隊</h3>
<table id="tableSelected">
<thead><tr><th>球隊</th><th>得分</th></tr></thead>
<tbody><tr class="empty-hint"><td colspan="2">尚未選擇任何球隊</td></tr></tbody>
</table>
</div>
<script>
$(function() {
const $source = $('#tableToSelect tbody');
const $target = $('#tableSelected tbody');
// 點擊行移動
$source.on('click', 'tr', function() {
const $row = $(this).detach(); // 從原處移除並保留 jQuery 物件
// 移除空狀態提示
$target.find('.empty-hint').remove();
// 取消懸停樣式,加入選中樣式
$row.removeAttr('style').css('cursor', 'default')
.off('click') // 移除點擊事件,避免重複移動
.appendTo($target);
});
// 懸停視覺回饋 (可選,CSS :hover 已處理,此處示範 JS 方式)
$source.on('mouseenter', 'tr', function() {
$(this).addClass('hover');
}).on('mouseleave', 'tr', function() {
$(this).removeClass('hover');
});
});
</script>
</body>
</html>
.detach() vs .remove()| 方法 | 返回值 | 事件/資料保留 | 適用場景 |
|---|---|---|---|
detach() | jQuery 物件 (含事件/資料) | ✅ 保留 | 暫時移除,稍後重新插入 |
remove() | jQuery 物件 (事件/資料清除) | ❌ 清除 | 永久刪除 |
本例使用 detach() 保留行內潛在的事件綁定 (雖然本例移除了 click),符合「移動而非刪除」的語意。
tbody 而非 table:避免誤移動 thead/tfoot.on() 事件委派:支援動態新增的行 (本例源表格靜態,目標表格動態)// 目標表格也支援點擊移回
$target.on('click', 'tr', function() {
$(this).detach().appendTo($source).css('cursor', 'pointer').on('click', sourceClickHandler);
if ($target.children().length === 0) {
$target.append('<tr class="empty-hint"><td colspan="2">尚未選擇任何球隊</td></tr>');
}
});
利用 jQuery 的 detach() + appendTo() 組合,配合事件委派與視覺回饋,能以極少程式碼實現直觀的雙向表格行移動交互,廣泛適用於商品選購、權限分配、任務排程等場景。