首页 > 解决方案 > 单独的复制按钮以复制单独的输入字段而没有冗余

问题描述

我有这个(我知道这是错误的):

function copy() {
    var copyText = document.getElementById("copy_");
    copyText.select();
    copyText.setSelectionRange(0, 99999)
    document.execCommand("copy");
}
function copy2() {
    var copyText2 = document.getElementById("copy_2");
    copyText2.select();
    copyText2.setSelectionRange(0, 99999)
    document.execCommand("copy2");
}

它链接到这些:

<ol>
<li><p>Open Terminal and change directory to /test/:</p><input type="text" value="cd /Users/test/" id="copy_" disabled><button onclick="copy()">Copy</button></li>

<li><p>Make a directory:</p><input type="text" value="mkdir .test" id="copy_2" disabled><button onclick="copy2()">Copy</button></li>
</ol>

我被告知我的一些同事使用事件对象,querySelectorAll但我不确定如何合并它。

提前致谢

标签: javascriptfunctioninputcopy

解决方案


在这种情况下,我不确定是否使用事件对象和 querySelectorAll。

但是您有 2 种类似的方法,它们在元素的“id”方面有所不同。

创建一个将元素的“id”作为函数参数的方法

jsfiddle

function copy(id) {
    var copyText = document.getElementById(id);
    copyText.select();
    copyText.setSelectionRange(0, 99999)
    document.execCommand("copy");
}

推荐阅读