优化从输入字段复制数据的javascript onclick函数

优化从输入字段复制数据的javascript onclick函数,javascript,html,copy,clipboard,input-field,Javascript,Html,Copy,Clipboard,Input Field,我有一个javascript函数,可以将文本输入字段中的信息复制到剪贴板,它的功能很好。但是,我需要这个函数能够处理多个输入或将多个onclick事件连接到同一个输入字段 基本上,我正在寻找优化以下内容的方法 function h1Function() { var copyText1 = document.getElementById("h1Input"); copyText1.select(); document.execCommand("copy"); alert("Copied the t

我有一个javascript函数,可以将文本输入字段中的信息复制到剪贴板,它的功能很好。但是,我需要这个函数能够处理多个输入或将多个onclick事件连接到同一个输入字段

基本上,我正在寻找优化以下内容的方法

function h1Function() {
var copyText1 = document.getElementById("h1Input");
copyText1.select();
document.execCommand("copy");
alert("Copied the text: " + copyText1.value);
}
function h2Function() {
var copyText2 = document.getElementById("h2Input");
copyText2.select();
document.execCommand("copy");
alert("Copied the text: " + copyText2.value);
}
已连接到以下html字段

<h1><a href="#" onclick="h1Function()">abcdefg123456ABCDEFG - h1</a></h1>
<input type="text" value="<div class='h1 highlight'>Din tekst her</div>" 
id="h1Input" />
<h2><a href="#" onclick="h2Function()">abcdefg123456ABCDEFG - h2</a></h2>
<input type="text" value="<div class='h2 highlight'>Din tekst her</div>" 
id="h2Input" />

只要将id作为参数传递给函数,任何和所有优化提示都将受到欢迎

函数h1Functionid{ var copyText1=document.getElementByIdid; copyText1.select; 文件副本; alertCopied文本:+copyText1.value; }
将输入的id作为参数传递给H1Function这应该发布在codereview.stackexchange.com上,因为这是一个更适合增强请求的位置。因为这两个函数做相同的事情,只是在不同的元素上,您只需要一个函数,就可以使用this.parentElement.nextElementSibling而不是元素引用。您也不应该使用超链接,这些超链接不能在任何地方导航,只是作为一些JavaScript的挂钩。您可以向任何可见元素添加单击事件处理程序,这样您就可以使h1具有onclick。我会给您正确的答案,但是我要补充的是,我还包括了Scott Marcus的解决方案,即向元素添加onclick事件,而不是死链接。