下面的HTML代码是一个循环结果.我想要的只是通过单击按钮来复制输入值,但我无法使其工作.

function myFunction() {
  // Get the text field
  var copyText = document.getElementById("myInput");

  // Select the text field
  copyText.select();
  copyText.setSelectionRange(0, 99999); // For mobile devices

  // Copy the text inside the text field
  navigator.clipboard.writeText(copyText.value);

  // Alert the copied text
  alert("Copied the text: " + copyText.value);
}
<input type="text" value="Hello World" id="myInput">
<button onclick="myFunction()">Copy text</button>

<input type="text" value="Hello World fdasfds" id="myInput">
<button onclick="myFunction()">Copy text</button>

<input type="text" value="Hello World fdasfd fsdafds" id="myInput">
<button onclick="myFunction()">Copy text</button>

如果只有一个条目,则它可以完美地工作.

function myFunction() {
  // Get the text field
  var copyText = document.getElementById("myInput");

  // Select the text field
  copyText.select();
  copyText.setSelectionRange(0, 99999); // For mobile devices

  // Copy the text inside the text field
  navigator.clipboard.writeText(copyText.value);

  // Alert the copied text
  alert("Copied the text: " + copyText.value);
}
<input type="text" value="Hello World fdasfd fsdafds" id="myInput">
<button onclick="myFunction()">Copy text</button>

推荐答案

识别符之所以称为识别符,是因为它标识一个元素.如果您将其用于三个元素,则只有第一个ID生效,而浏览器将忽略其他元素.

对于三个输入域,使用三个不同的ID.

示例

function myFunction(id) {
  // Get the text field
  var copyText = document.getElementById(id);

  // Select the text field
  copyText.select();
  copyText.setSelectionRange(0, 99999); // For mobile devices

  // Copy the text inside the text field
  navigator.clipboard.writeText(copyText.value);

  // Alert the copied text
  alert("Copied the text: " + copyText.value);
}
<input type="text" value="Hello World 1st input" id="myInput-1">
<button onclick="myFunction('myInput-1')">Copy text</button>

<input type="text" value="Hello World 2nd input" id="myInput-2">
<button onclick="myFunction('myInput-2')">Copy text</button>

<input type="text" value="Hello World 3rd input" id="myInput-3">
<button onclick="myFunction('myInput-3')">Copy text</button>

更多信息

Javascript相关问答推荐

如何为GrapesJS模板编辑器创建自定义撤销/重复按钮?

未捕获错误:在注销后重定向到/login页面时找不到匹配的路由

如何禁用附加图标点击的v—自动完成事件

有没有可能使滑动img动画以更快的速度连续?

处理时间和字符串时MySQL表中显示的日期无效

在我的html表单中的用户输入没有被传送到我的google表单中

屏幕右侧屏障上的产卵点""

Angular 中的类型错误上不存在获取属性

本地库中的chartjs-4.4.2和chartjs-plugin-注解

检索相加到点的子项

使用Nuxt Apollo在Piniastore 中获取产品细节

如何确保预订系统跨不同时区的日期时间处理一致?

将嵌套数组的元素乘以其深度,输出一个和

JavaScript -复制到剪贴板在Windows计算机上无效

无法使用Redux异步函数读取未定义的useEffect钩子的属性';map';

连续添加promise 时,如何在所有promise 都已结算时解除加载覆盖

更改管线时不渲染组件的react

使用静态函数保存 node 前的钩子

如何在不将整个文件加载到内存的情况下,在Node.js中实现Unix粘贴命令?

MUI-TABLE:MUI表组件中交替行的不同 colored颜色 不起作用