javascript - HTML按钮选择表格上的特定列
问题描述
我想知道如何选择表格上的特定列..
此功能使选择所有表...我只想选择标题 2,3 和仅父...像这张图片:
我想为复制列选择文本(Ctrl+C)...
我正在尝试这个并努力选择桌子上的所有内容......
function selectElementContents(el) {
var body = document.body,
range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
sel.removeAllRanges();
try {
range.selectNodeContents(el);
sel.addRange(range);
} catch (e) {
range.selectNode(el);
sel.addRange(range);
}
} else if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(el);
range.select();
}
}
#thead {
background-color: #fffd99;
}
#table,
th,
td {
border: 1px solid black;
}
<input type="button" value="select table" onclick="selectElementContents( document.getElementById('table') );">
<br>
<table id="table">
<thead>
<tr>
<th>Code</th>
<th>Heading 1</th>
<th>Heading 2</th>
<th>Heading 3</th>
</tr>
<thead>
<tbody>
<tr>
<td>1774</td>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
</tr>
<tr>
<td>1774</td>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
</tr>
<tr>
<td>1774</td>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
</tr>
</tbody>
</table>
解决方案
$('table th').click(function(){
if($(this).hasClass("selected")){
$(this).removeClass("selected");
columnIndex = $(this).index() + 1;
$('table tr td:nth-child(' + columnIndex + ')').removeClass("selected");
}else{
$(this).addClass("selected");
columnIndex = $(this).index() + 1;
$('table tr td:nth-child(' + columnIndex + ')').addClass("selected");
$('table tr td:nth-child(' + columnIndex + ')').each(function(){
console.log('Selected value:',$(this).html());
});
}
});
.selected{
color:#0000FF;
background-color:#000000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table cellspacing="2" cellpadding="4" border="1px">
<tr>
<th>HEAD 1</th>
<th>HEAD 2</th>
<th>HEAD 3</th>
</tr>
<tr>
<td>DATA 1</td>
<td>DATA 2</td>
<td>DATA 3</td>
</tr>
<tr>
<td>DATA 1</td>
<td>DATA 2</td>
<td>DATA 3</td>
</tr>
<tr>
<td>DATA 1</td>
<td>DATA 2</td>
<td>DATA 3</td>
</tr>
<tr>
<td>DATA 1</td>
<td>DATA 2</td>
<td>DATA 3</td>
</tr>
<tr>
<td>DATA 1</td>
<td>DATA 2</td>
<td>DATA 3</td>
</tr>
</table>
希望这会帮助你。单击“头”并选择“整列”。
推荐阅读
- dpdk - 如何使用一个 NIC 设置循环转发以在 DPDK testpmd 中发送数据包并自行接收它们?
- flutter - Dialogflow 版本flutter失败
- python-3.x - 在 tkinter 中绘制图形
- vlookup - 根据分配表中的通配符分配类别值
- mongodb - 连接到 mongodb 时出现错误
- python-3.x - 如何访问具有特定格式的字典的所有键值
- elastic-stack - 如何使用 filebeat 读取自定义日志文件并使用 kibana 读取和创建数据的可视化
- python - 将键发送到搜索框时元素不可交互
- php - 如何获取显示数据已找到和未找到的结果
- python-3.x - 在使用双向 RNN 模型时,我不断收到错误“'tuple' object has no attribute 'size'”