如何使用Django模板和JavaScript将HTML表列的值复制到剪贴板?

zzoitvuj  于 2023-11-20  发布在  Go
关注(0)|答案(1)|浏览(127)

我需要将HTML表格列的值复制到剪贴板。我使用Django模板。

这是我的HTML表:

<table>
                    <tr>
                        <th>Name</th>
                        <th>DOB</th>
                        <th>ID</th>
                        <th>Guardian</th>
                        <th>Email</th>
                        <th>Telephone</th>
                        <th>NIF</th>
                        <th>Notes</th>
                    </tr>
                    {% for a in sessao.first %}
                       <tr>
                          <td>{{ a.nome }}</td>
                          <td>{{ a.dtnasc }}</td>
                          <td>{{ a.alunoid }}</td>
                          <td>{{ a.educaid }}</td>
                          <td id="a.id">{{ a.educaid.email }}</td>
                          <td>{{ a.educaid.telefonea }}</td>
                          <td>{{ a.nif }}</td>
                          <td>{{ a.notas }}</td>
                          <td><button class="btn btn-outline-success btn-sm" onclick="CopyText({{ a.id }})" data-toggle="tooltip" data-placement="top" title="Copy">
                               copy
                           </button>
                          </td> 
                        </tr>
                    {% endfor %}
                </table>

字符串

我正在尝试此脚本,但收到错误消息:

// Copy to ClipBoard
 function CopyText(el) {
 // Get the Selected Data By ID
  var copyText = document.getElementById(`${el}`)

  var str = copyText.innerHTML // Get All HTML Data and Copy to Clipboard

   function listener(e) {
    e.clipboardData.setData("text/plain", str);
    e.preventDefault();
  }
  document.addEventListener("copy", listener);
  document.execCommand("copy");
  document.removeEventListener("copy", listener);
};


错误消息为:

Uncaught TypeError: Cannot read properties of null (reading 'innerHTML')
    at CopyText (lu.js:11:22)
    at HTMLButtonElement.onclick (2/:80:159)


任何帮助都将不胜感激。先谢了。

7fhtutme

7fhtutme1#

在这种情况下,因为您的id属性设置为普通字符串,并且您试图检索的元素不存在。此外,函数param没有正确传递:

<table>
    ...

    {% for a in sessao.first %}
    <tr>
        ...
        <td id="a-{{a.id}}">{{ a.educaid.email }}</td>
        ...
        <td><button class="btn btn-outline-success btn-sm" onclick="CopyText('{{a.id}}')" data-toggle="tooltip"
                data-placement="top" title="Copy">
                copy
            </button>
        </td>
    </tr>
    {% endfor %}
</table>
<script>
    const CopyText = (id) => {
        const text = document.getElementById(`a-${id}`).innerHTML;
        navigator.clipboard.writeText(text);
    }
</script>

字符串

相关问题