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

时间:2019-02-26 12:27:59

标签: javascript php html button

我正在为网站创建表格。网站在表中返回其值。我需要复制表td的所有值,并将它们粘贴到excel中。有没有办法做一个“全选”按钮,这样我只需要按ctrl + c?而不是将鼠标一直拖到桌子下方。

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

我在这里使用的表格代码:

<!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>

1 个答案:

答案 0 :(得分:0)

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') );">

它应该工作;)

链接来自: Select a complete table with Javascript