我正在调试其他人的代码,并且第一次单击“复制”功能即可,但是对于任何后续尝试,都需要单击两次以进行复制。我不知道是什么原因造成的。
通过选中用户要复制的框,然后单击“复制”来选择每个节点。然后可以将复制的数据粘贴到Excel或类似文件中。
HTML:
<li id="copy">
<a title="Copy Contents Of Records" data-source="dbTable" href="#" ng-click="copyRow($event)" ng-class="{'disabled' : ShowLoading}"><i class="fa fa-paste"></i></a>
</li>
JAVASCRIPT:
$scope.copyRow = function ($event) {
$event.preventDefault();
let head = [];
angular.forEach($scope.data.objColumns,
function (col) {
head.push(col.strColumnName);
});
let rows = [];
angular.forEach($scope.data.objColumnData,
function (item) {
if (item.bolSelected) {
let row = [];
angular.forEach(item.columnData,
function (data) {
row.push(data.strColumnDisplayValue);
});
rows.push(row);
}
});
let virtualTable = document.createElement('table');
virtualTable.id = "virTab";
// For table head
for (let i = 0; i < head.length; i++) {
let th = document.createElement('th');
th.innerHTML = head[i];
virtualTable.appendChild(th);
}
// For table body
for (let i = 0; i < rows.length; i++) {
console.log(rows[i]);
let tr = document.createElement('tr');
for (let j = 0; j < rows[i].length; j++) {
let td = document.createElement('td');
td.innerHTML = rows[i][j];
td.removeAttribute('style');
tr.appendChild(td);
}
tr.removeAttribute('style');
virtualTable.appendChild(tr);
}
virtualTable.removeAttribute('style');
document.body.appendChild(virtualTable);
// Invoke copying function
let textRange;
if (isIE()) {
textRange = document.body.createTextRange();
textRange.moveToElementText(document.getElementById('virTab'));
textRange.execCommand("copy");
} else {
textRange = document.createRange();
textRange.selectNode(document.getElementById('virTab'));
window.getSelection().addRange(textRange);
const success = document.execCommand('copy');
let msg = success ? 'Success' : 'Failure';
console.log(msg);
window.getSelection().removeAllRanges();
}
答案 0 :(得分:0)
问题在于,需要在以下位置清除选择:
textRange.selectNode(document.getElementById('virTab'));
解决方案是添加
window.getSelection().removeAllRanges();
到“ else”语句的开头。