Javascript将表格单元格复制到剪贴板的左侧

时间:2019-02-24 11:43:08

标签: javascript json crud

我在尝试将ID分配给使用javascript创建的表时遇到困难。我希望能够定位到特定的表行(左侧的行),并将该内容作为纯文本复制到剪贴板。

例如,在单元格1中填充“ NAME”字段的特定ID,以过滤搜索结果。我希望能够将复制按钮插入到cell3中以从cell2(NAME)复制数据

任何帮助将不胜感激!

Example of how tool is supposed to work

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";
        }
      }       
    }
  }

1 个答案:

答案 0 :(得分:0)

这可以帮助您:

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>