我需要从网页表格内容复制到剪贴板。当然,我想按“选择表格”按钮,然后选择所有需要的内容,然后用户按 Ctrl + C 或 Shift + Ins ,就在这里。我无法选择<thead>
和<tbody>
内容的麻烦。现在我有以下代码:
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();
}
};
function SelectTable () {
selectElementContents(document.getElementById('resbody'));
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="results">
<caption>Results</caption>
<thead id="reshead">
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</thead>
<tbody id="resbody">
<tr><td>1</td><td>2</td><td>3</td></tr>
<tr><td>4</td><td>5</td><td>6</td></tr>
<tr><td>7</td><td>8</td><td>9</td></tr>
</tbody>
<tfoot>
<td colspan="3"><button onclick="SelectTable();">Select table</button></td>
</tfoot>
</table>
现在代码选择表格内容。
如果我想尝试做类似的事情:
var a=document.getElementById('reshead');
var b=document.getElementById('resbody');
var c=a.concat(b);
selectElementContents(c);
根本不起作用。 甚至
var a=document.getElementById('resbody');
selectElementContents(a);
不起作用:-O我可以用jQuery更简单吗?
答案 0 :(得分:1)
您可以通过添加
来实现
selectElementContents(document.getElementById('reshead'));
在selectTable
功能和删除行中
sel.removeAllRanges();
来自selectElementContents
函数,因此它不会覆盖先前选定的区域。
请参阅以下修改过的代码段,它适用于我。标题和内容都被选中
function selectElementContents(el) {
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
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();
}
};
function SelectTable () {
selectElementContents(document.getElementById('resbody'));
selectElementContents(document.getElementById('reshead'));
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="results">
<caption>Results</caption>
<thead id="reshead">
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</thead>
<tbody id="resbody">
<tr><td>1</td><td>2</td><td>3</td></tr>
<tr><td>4</td><td>5</td><td>6</td></tr>
<tr><td>7</td><td>8</td><td>9</td></tr>
</tbody>
<tfoot>
<td colspan="3"><button onclick="SelectTable();">Select table</button></td>
</tfoot>
</table>