繁体   English   中英

javascript将HTML输入类型ID传递给函数

[英]javascript pass html input type id to function

假设我有一个带有Javascript事件的以下HTML元素列表,用于将HTML输入类型文本的内容复制到剪贴板中:

<input type="text" size="70" value="something1" id="v1">
<button onclick="CopyToClipboard('v1')">Copy command</button>

<input type="text" size="70" value="something2" id="v2">
<button onclick="CopyToClipboard('v2')">Copy command</button>

等等..

如何使用javascript复制txt?

我正在尝试调整下面的代码,但我不知道如何将HTML ID传递给javascript代码。 我知道getElementById()在那种情况下是不正确的,不应调用。 但是我不知道如何将id值传递到Javascript函数中。

<script>
function CopyToClipboard(myInput) {
  /* Get the text field */
  var copyText = document.getElementById("myInput");

  /* Select the text field */
  copyText.select(myInput);

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}
</script>

任何帮助将不胜感激。

谢谢

错误是您使用document.getElementById("myInput")而不是document.getElementById(myInput)

 function CopyToClipboard(myInput) { /* Get the text field */ var copyText = document.getElementById(myInput) // pass dynamic value here console.log(copyText) /* Select the text field */ copyText.select(myInput); /* Copy the text inside the text field */ document.execCommand("copy"); /* Alert the copied text */ alert("Copied the text: " + copyText.value); } 
 <input type="text" size="70" value="something1" id="v1"> <button onclick="CopyToClipboard('v1')">Copy command</button> <input type="text" size="70" value="something2" id="v2"> <button onclick="CopyToClipboard('v2')">Copy command</button> 

暂无
暂无

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

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