首页 > 解决方案 > TypeError:text.select 不是函数

问题描述

我正在尝试使用 js 实现复制到剪贴板功能。
我有一张桌子:

<tbody>
            <tr>
                <td>1.</td>
                <td id="kord">(35|154)</td>
                <td id="gorj">15</td>
                <td>3,6</td>
                <td><button type="button" onclick="copyKord()">Kopiraj</button></td>
                <td><button type="button" onclick="copyGorj()">Kopiraj</button></td>
                <td><input type="number"></td>
            </tr>
</tbody>

我的js函数:

    function copyKord(){
    var text = document.getElementById("kord").innerHTML;
    console.log(text);
    text.select();
    document.execCommand("copy");
}

因此,当我按下按钮时,当我 console.log 显示文本的变量时,出现错误“TypeError:text.select 不是 copyKord 的函数”。我尝试使用插入 td 元素的 textarea ,但它仍然无法正常工作。

标签: javascripthtml

解决方案


您可以使用navigator.clipboard.writeText来执行copy操作。

function copyKord(){
    var text = document.getElementById("kord").innerHTML;
    navigator.clipboard.writeText(text);
}

function copyGorj() {
  var text = document.getElementById("gorj").innerHTML;
    navigator.clipboard.writeText(text);
}
<table>
  <tbody>
            <tr>
                <td>1.</td>
                <td id="kord">(35|154)</td>
                <td id="gorj">15</td>
                <td>3,6</td>
                <td><button type="button" onclick="copyKord()">Kopiraj</button></td>
                <td><button type="button" onclick="copyGorj()">Kopiraj</button></td>
                <td><input type="number"></td>
            </tr>
  </tbody>
</table>


推荐阅读