首页 > 解决方案 > 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>

标签: javascripthtml

解决方案


$('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>

希望这会帮助你。单击“头”并选择“整列”。


推荐阅读