我想在javascript中动态创建一个表,并将其作为表放在剪贴板中。就像我们将值粘贴到电子邮件或word文档中一样,它会自动显示为表格。
我正在使用此代码将数据放入剪贴板(可在plunker上找到)
$(document).ready(function(){
var data = [
{lastName:'Doe', firstName:'John', birthday: '01.01.2001'},
{lastName:'Doe', firstName:'Jane', birthday: '02.02.2002'},
{lastName:'Foo', firstName:'Bar', birthday: '03.03.2003'}
];
var exportResult = '<table><tr><th> Last name</th><th> First name</th><th> Birthday </th></tr>';
for (var i = 0; i < data.length; i++) {
exportResult += '<tr><td>' + data[i].lastName + '</td><td>' + data[i].lastName + '</td><td>' + data[i].lastName + '</td></tr>'
}
exportResult += '</table>';
$("button").click(function(){
var textarea = '<textarea>' + exportResult + '</textarea>';
$("body").append(textarea);
$("textarea").select();
try {
var successful = document.execCommand('copy');
if (!successful) throw successful;
} catch (err) {
window.prompt("Copy to clipboard: Ctrl+C, Enter", toCopy);
}
$("textarea").remove();
});
});
但是当我在word doc或email中通过它时,这是原始纯文本,而不是html表。
答案 0 :(得分:0)
此代码有效:
$(document).ready(function(){
var data = [
{lastName:'Doe', firstName:'John', birthday: '01.01.2001'},
{lastName:'Doe', firstName:'Jane', birthday: '02.02.2002'},
{lastName:'Foo', firstName:'Bar', birthday: '03.03.2003'}
];
var exportResult = '<table id="tableToCopy"><tr>' +
'<th> Last name</th>' +
'<th> First name</th>' +
'<th> Birthday </th>' +
'</tr>';
for (var i = 0; i < data.length; i++) {
exportResult += '<tr>' +
'<td>' + data[i].lastName + '</td>' +
'<td>' + data[i].lastName + '</td>' +
'<td>' + data[i].lastName + '</td>' +
'</tr>'
}
exportResult += '</table>';
$("button").click(function(){
$("body").append(exportResult);
var body = document.body, range, sel, el= document.getElementById('tableToCopy');
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();
range.execCommand("Copy");
}
document.execCommand('copy');
$("table").remove();}
);
});