dongmou2389 2019-02-26 12:27
浏览 224
已采纳

如何为表创建“全选”按钮

I am creating an table for an website. The website returns its values in an table. i need to copy all values from the table td's, and paste them in excel. is there a way to make a "select all" button, so that i only need to press ctrl+c? Instead of dragging my mouse all the way down the table.

I want outcome to be like this (if I press the button)

Code of the table i used here:

<!DOCTYPE html>
<html>
<head>
    <style>
        table,
        th,
        td {
            border: 1px solid black;
            border-collapse: collapse;
        }
    </style>
</head>
<body>
    <h2>Select all test</h2>
    <button type="button">Select all</button>
    <table style="width:80%">
        <tr>
          <th>Name</th>
          <th>Lastname</th>
          <th>Age</th>
        </tr>
        <tr>
            <td>Henk</td>
            <td>Bakker</td>
            <td>46</td>
        </tr>
        <tr>
            <td>Fedde</td>
            <td>hooghouts</td>
            <td>67</td>
        </tr>
    </table>
</body>
</html>

</div>
  • 写回答

1条回答 默认 最新

  • dtu36380 2019-02-26 12:36
    关注

    JS:

    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();
            }
        }
    

    HTML:

    <table id="tableId" border="1">
        <thead>
            <tr><th>Heading 1</th><th>Heading 2</th></tr>
        </thead>
        <tbody>
            <tr><td>cell 1</td><td>cell 2</td></tr>
        </tbody>
    </table>
    
    <input type="button" value="select table" onclick="selectElementContents( document.getElementById('tableId') );">
    

    It should work ;)

    Link from: Select a complete table with Javascript

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?