繁体   English   中英

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

[英]How can i send text from element with id to function on click?

我希望当我按下按钮时它会复制“你好”但我收到这个错误: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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM