简体   繁体   English

如何使用js复制到剪贴板按钮

[英]how to make a copy to clipboard button with js

so i was trying to make a button that when clicked it copy a value from a variable所以我试图制作一个按钮,当点击它时,它会从变量中复制一个值

like喜欢

<button onclick="copyToClipboard()">COPY</button>

and then on that function it takes the element to copy from a variable like然后在 function 上,它需要从变量中复制元素,例如

var copyids = {
"ids": [
{
"name": "id1",
"id": 192389021
},
{
"name": "id2",
"id": 123879032
},
{
"name": "id3",
"id": 149018292
},
]
};

so like copyids.ids[0].id and it copy that value就像copyids.ids[0].id一样,它会复制该值

i hope its understandable我希望它可以理解

To copy, you will need to select before what you want to copy.要复制,您需要先 select,然后再复制。 Maybe you should put the data of the variable somewhere and copy it.也许您应该将变量的数据放在某处并复制它。

https://www.w3schools.com/howto/howto_js_copy_clipboard.asp https://www.w3schools.com/howto/howto_js_copy_clipboard.asp

Maybe this helps也许这有帮助

function copyToClipboard() {
    let temp = document.createElement('textarea');
    temp.value = copyids.ids[0].id;
    document.body.appendChild(temp);
    temp.select();
    document.execCommand('copy');
    document.body.removeChild(temp);
}

I made you a solution with the ability to select the desired data cell from the array.我为您提供了一个解决方案,它能够 select 从阵列中获取所需的数据单元。 I've added a select tag for you, listing the name of each cell.我为您添加了select标签,列出了每个单元格的名称

And at the choice of a specific option with you copy id in accordance with the specified name .并在选择特定option时与你按照指定的名称复制id

 function copyToClipboard() { var copyids = { ids: [ { name: "id1", id: 192389021, }, { name: "id2", id: 123879032, }, { name: "id3", id: 149018292, }, ], }; let selectIndex = document.querySelector("select").selectedIndex; let storage = document.createElement("input"); storage.value = copyids.ids[selectIndex].id; console.log(storage.value); document.body.appendChild(storage); storage.select(); document.execCommand("copy"); document.body.removeChild(storage); }
 <button onclick="copyToClipboard()">COPY</button> <select> <option value="id1">id1</option> <option value="id2">id2</option> <option value="id3">id3</option> </select>

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

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