我试图在我的网站上创建多个按钮来将相应的文本复制到剪贴板,但所有按钮似乎都在复制最后的文本。
我为要复制的每个文本使用了不同的
id
属性,并在该文本的 JavaScript id
区域中使用了匹配的 getElementById()
属性。
我想也许我需要为每个函数使用独特的
onclick()
函数,而不是为所有函数使用 copyClipboard()
。
P.S:我不是程序员,我更像是一个脚本小子。
这是我使用的代码...
(两个按钮最终都会复制第二个文本。我希望每个按钮复制其各自的文本。)
<script>
function copyClipboard() {
var copyText = document.getElementById("one").innerHTML;
var input = document.createElement("input");
input.value = copyText;
document.body.appendChild(input);
input.select();
document.execCommand("copy");
document.body.removeChild(input);
}</script>
<button onclick="copyClipboard()">copy</button>
<p id="one">first</p>
<script>
function copyClipboard() {
var copyText = document.getElementById("two").innerHTML;
var input = document.createElement("input");
input.value = copyText;
document.body.appendChild(input);
input.select();
document.execCommand("copy");
document.body.removeChild(input);
}</script>
<button onclick="copyClipboard()">copy</button>
<p id="two">second</p>
以下内容会将文本复制到剪贴板 - 希望有帮助。
<html>
<head>
<script>
function copy_to_clipboard( elm_id ) {
var text = document.getElementById( elm_id ).innerHTML;
navigator.clipboard.writeText( text );
}
</script>
</head>
<body>
<button onclick="copy_to_clipboard('one')">copy first</button>
<p id="one">first</p>
<button onclick="copy_to_clipboard('two')">copy second</button>
<p id="two">second</p>
</body>
</html>