The clipboard.js plugin cares about binding the "what to copy" with the buttons using the data-clipboard-target
attribute. So an id
has to be defined inline.
You can do it using a unique id
generated in the table creation loop, using the singleRow
index.
Now, what's to be copied has to be an input
... Not a td
, because clipboard gets the text to copy using the value... Not the inner HTML.
You can style your input so it doesn't look like an input! Use the beginning of the id
to style it. It is disabled in the generated markup I suggest.
input[id^='toCopy']{
border:0;
outline:0;
}
Then, you just have to instantiate the plugin on the button class. Here I strongly suggest you use a class that has no chance to be already used somewhere else. In their documentation, they suggest .btn
... But that is way too common. I suggest .cb_btn
(cb as in clipboard).
Below is your csvToTable function modified.
Notice the cellToCopyIndex
index that you will have to check. It has to be a zero-based integer corresponding to the column you wish to copy.
function csvToTable(myReturn){
var cellToCopyIndex = 2; // The index of the cell to be copied, zero based
var allRows = myReturn.split(/
?
|
/);
var table = '<table class="tablesorter">';
for (var singleRow = 0; singleRow < allRows.length; singleRow++) {
if (singleRow === 0) {
table += '<thead>';
table += '<tr>';
} else {
table += '<tr>';
}
var rowCells = allRows[singleRow].split(',');
for (var rowCell = 0; rowCell < rowCells.length; rowCell++) {
if (singleRow === 0) {
table += '<th style="padding: 15px;">';
table += clearString(rowCells[rowCell]);
table += '</th>';
} else {
table += '<td>';
if(rowCell==cellToCopyIndex){
table += '<input type="text" id="toCopy_'+singleRow+'" value="'+clearString(rowCells[rowCell])+'" readonly>';
}else{
table += clearString(rowCells[rowCell]);
}
table += '</td>';
}
}
if (singleRow === 0) {
table += '</tr>';
table += '</thead>';
table += '<tbody>';
} else {
table += '</td><td><button class="cb_btn" data-clipboard-target="#toCopy_'+singleRow+'"><img src="assets/clippy.svg" alt="Copy to clipboard"></button></td></tr>';
}
}
table += '</tbody>';
table += '</table>';
return table;
}
To instantiate the plugin, do it when the table is created... That is in your Ajax success callback:
success: function(response){
///console.log(response)
jQuery('#returndatalog').css('display', 'block');
if(typeof response =='object')
{
var myReturn = response.response;
if (csv) {
jQuery(domElement).html(csvToTable(myReturn));
jQuery(domElement + " table").tablesorter();
new Clipboard('.cb_btn'); // Instantiate Clipboard here.
}
else {
jQuery(domElement).html(response.response.replace(/"/g,""));
}
}
if(response.error){
}
else{
}
},
Disclaimer: Fully untested!! ;)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…