首页 > 解决方案 > 如何将复制按钮链接到表格中的单元格?

问题描述

我有一个复制按钮脚本:

function myFunction() {
    var table = document.getElementById('myTable');
    var copyText = table.rows[1].cells[0].innerHTML;
    copyText.select();
    document.execCommand("copy");
    alert("Copied");
}

我的桌子:

<table id="myTable">
{% for resp in results %}
        <tr>
            <td>{{ resp }}</td>
            <td>{{ resp.Question_id.Statement }}</td>
            <td><button onclick="myFunction()">Copy text</button></td>
        </tr>
    {% endfor %}
</table>    

我希望按钮复制 td {{ resp }} /td 中的文本

标签: htmlbuttonhtml-table

解决方案


function myFunction(val, event) {
  var inp = document.createElement('input');
  document.body.appendChild(inp)
  inp.value = val;
  inp.select();
  document.execCommand('copy', false);
  inp.remove();
  alert('copied');
}
<table id="myTable">
  <tr>
    <td>one</td>
    <td><button onclick="myFunction('one')">Copy text</button></td>
  </tr>

  <tr>
    <td>two</td>
    <td><button onclick="myFunction('two')">Copy text</button></td>
  </tr>

  <tr>
    <td>three</td>
    <td><button onclick="myFunction('three')">Copy text</button></td>
  </tr>

  <tr>
    <td>four</td>
    <td><button onclick="myFunction('four')">Copy text</button></td>
  </tr>

</table>

一个快速的解决方案是将text函数中的(要复制的)作为 argu 传递。 ctrl + v看看结果。


推荐阅读