[英]Select only one table cell per row and column
我有下表:
<table border="1" cellpadding="5" class="test">
<tr>
<td id="1">aaa</td>
<td id="2">bbb</td>
<td id="3">ccc</td>
</tr>
<tr>
<td id="4">ddd</td>
<td id="5">eee</td>
<td id="6">fff</td>
</tr>
<tr>
<td id="7">ggg</td>
<td id="8">hhh</td>
<td id="9">iii</td>
</tr>
</table>
條件應該是每行每列只能選擇一個表格單元格。
目前我的腳本正在管理每個表格列只能選擇一個,但是我如何另外添加每個表格行也只能選擇一個單元格。
這是我的腳本和JS Fiddle :
$(document).on("click", ".test td", function() {
let index = $(this).index()+1;
$(this)
.closest('table')
.find('tr>td:nth-child('+index+')')
.removeClass('selected');
var col1 = $(this).addClass('selected').text();
});
刪除單擊行中的所有active
類。 將以下行插入您的代碼
$(this).closest('tr').find('td').removeClass('selected');
所以,
$(document).on("click", ".test td", function() {
let index = $(this).index()+1;
$(this)
.closest('table')
.find('tr>td:nth-child('+index+')')
.removeClass('selected');
$(this).closest('tr').find('td').removeClass('selected'); // remove 'active' class of the row
var col1 = $(this).addClass('selected').text();
});
選擇“每個表格行一個單元格”的解決方案
$(document).on("click", ".test td", function() {
let index = $(this).index()+1;
console.log(index)
$(this)
.closest('tr').children('td')
.removeClass('selected');
$(this).addClass('selected')
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.