[英]Pressing button in row of table to copy cell to clipboard - Javascript
[英]Javascript copy table cell to the left to clipboard
我在嘗試將ID分配給使用javascript創建的表時遇到困難。 我希望能夠定位到特定的表行(左側的行)並將該內容作為純文本復制到剪貼板。
例如,在“名稱”字段中使用特定ID填充單元格1以過濾搜索結果。 我希望能夠將復制按鈕插入到cell3中以從cell2(NAME)復制數據
任何幫助,將不勝感激!
var table = document.createElement("table");
var header = table.createTHead();
var row = header.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "<b>ID</b>";
cell2.innerHTML = "<b>FAQ</b>";
cell3.innerHTML= "<b>COPY BUTTON</b>";
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < json.records.length; i++) {
tr = table.insertRow(-1);
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = json.records[i].ID;
tabCell = tr.insertCell(-1);
tabCell.innerHTML = json.records[i].NAME;
tabCell = tr.insertCell(-1);
tabCell.innerHTML = json.records[i].COPY BUTTON;
}
// ADD TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
document.getElementById("loader").style.visibility = "hidden";
$("#re").css("visibility","visible");
});
}
function myFunction() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("showData");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
這可以幫助您:
function CopyMyLeftTd(e) { var leftTdIndex= $(e).parent().index()-1; var leftTd= $(e).closest("tr").find("td:eq(" + leftTdIndex + ")"); copyToClipboard($(leftTd).text()); } function copyToClipboard(txt) { var el = document.createElement('textarea'); el.value = txt; el.setAttribute('readonly', ''); el.style.position = 'absolute'; el.style.left = '-9999px'; document.body.appendChild(el); el.select(); document.execCommand('copy'); document.body.removeChild(el); }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="banner-message"> <table class= 'table table-bordered'> <tr> <td>3</td> <td>text to be copied!</td> <td><button style="button" onclick="CopyMyLeftTd(this)" > Copy </button></td> </tr> </table> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.