I am trying to set a button to each td text in the table that will copy the contents to your clipboard.
I want to select the node contents of each text using jquery's this keyword. When I pass in the jQuery object it will throw an error.
It was working when I passed a unique ID, but when I passed a jQuery object it did not work. How can I achieve this efficiently?
$(document).ready( function() {
$('input[data-target]').on("click", function(){
var docSelector = document.createRange();
var get_text = $(this);
console.log(get_text);
console.log(docSelector.selectNodeContents(get_text));
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(docSelector);
document.execCommand("copy");
selection.removeAllRanges();
});
});
table, th, td{
border: 1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<table>
<thead>
<tr>
<th>Copy</th>
<th>Text</th>
</tr>
<tr>
<td> <input type="button" data-target='copy' value="X"></td>
<td id='copy'> Copy some text </td>
</tr>
<tr>
<td> <input type="button" data-target='copy1' value="X"></td>
<td id='copy1'> Copy some more text </td>
</tr>
<tr>
<td> <input type="button" data-target='copy2' value="X"></td>
<td id='copy2'> Copy some even more text </td>
</tr>
</thead>
</table>
</html>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…