简体   繁体   English

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

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

I want that when i press the button it will copy the "hello" but i get this error: copyText.select is not a function我希望当我按下按钮时它会复制“你好”但我收到这个错误:copyText.select 不是一个函数

how to fix it?如何解决?

<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>

You cannot select text of a span using select function.您不能使用选择功能选择跨度的文本。 You have to create a temporary input with the value of the text of the span.您必须使用跨度文本的值创建一个临时输入。 select the value in the input using select() and copy the text and then delete the input使用 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.

相关问题 如何将表单元素的自动生成的ID发送到javascript函数? - How can I send an automatically generated ID for a form element to a javascript function? 如何将选择为“文本”的SELECT框发送到按钮上的函数,以便使用angular进行ng-click? - How can I send a SELECT box selected “text” to a function on a button for ng-click using angular? 我如何在$ .click(jquery)中创建一个使用$ .click中的ID的函数 - How can I create a function inside an $.click (jquery) that uses an id from the $.click 如何使用 POST 请求将元素的 id 作为名称发送? - How can I send the id of an element as a name using POST request? 如何使整数列表单击具有相应 id 的元素? - How can I make a list of integers click on element with corresponding id? 如何通过鼠标单击从 chrome 扩展中获取当前选项卡的元素属性(文本、ID、类等..)? - How may I get the element attributes (text, id, class and so on..) of the current tab, out of a mouse click, from a chrome extension? 如何将form_id发送给javascript函数作为参数? - How can I send form_id to javascript function as a parameter? 如何发送不同的ID作为JS函数的参数? - How can I send a different ID as a parameter for a JS function? 如何在jQuery的ajax函数中从类访问元素ID? - How can I access the element ID from a class, within an ajax function in jQuery? 单击元素如何撤消外部功能? - How can I revoke an external function on click of an element?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM