javascript - 如何从具有 id 的元素发送文本以在单击时起作用?

标签 javascript html function onclick copy

我希望当我按下按钮时它会复制“你好” 但我收到此错误: copyText.select 不是函数

如何解决?

<html>
<head>
</head>
<body>
    <span id="aaa">hello</span>
    <button onclick="copy('#aaa')">copy</button>
    <script>
        function copy(text)
        {
            var copyText = text;
            copyText.select();
            document.execCommand("copy");
            console.log(document.getElementById('text'));
        }
    </script>
</body>

最佳答案

您无法使用选择功能选择跨度的文本。您必须使用范围文本的值创建一个临时输入。使用 select() 选择输入中的值并复制文本,然后删除输入

        function copy(text)
        {
            var copyText = document.getElementById(text).textContent;
            document.querySelector('#aux').innerHTML+=('<input id="a" value='+copyText+'>')
            document.getElementById("a").select();
            document.execCommand("copy");
            document.querySelector('#aux').innerHTML="";
            //console.log(document.getElementById('text'));
        }
   
<html>
<head>
</head>
<body>
    <span id="aaa">hello</span>
    <button onclick="copy('aaa')">copy</button>
   <span id="aux"></span>
</body>
</html>

关于javascript - 如何从具有 id 的元素发送文本以在单击时起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54576372/

相关文章:

html - 为什么显示 block 在输入字段焦点上不起作用?

javascript - 如何在Javascript中检测页面的宽度和高度?

javascript - 在javascript中将图片放入数组中

javascript - 我无法访问另一个文件中的函数

jquery - 使用 jquery 遍历表会给出未捕获的异常

c - 将结构数组传递给函数

javascript - 立即调用的简单 JavaScript 函数不起作用……为什么?

javascript - 如何防止子元素干扰 HTML5 dragover 和 drop 事件?

javascript - 如何隐藏数据属性

javascript - 此 Ajax javascript 代码无法正常工作