我编写此代码是为了使用唯一的按钮复制多个文本区域的内容,但仅复制第一个文本区域。
var copyText = document.getElementsByClassName("form-control")[0];
function myFunction() {
// Get the text field
// Select the text field
copyText.select();
copyText.setSelectionRange(0, 99999); // For mobile devices
// Copy the text inside the text field
document.execCommand("copy");
// Alert the copied text
alert("Copied the text: " + copyText.value);
///second
}
<textarea class="form-control" tabindex="0">something</textarea>
<button onclick="myFunction()">clickme</button>
<textarea class="form-control"tabindex="3" >something1</textarea>
<button onclick="myFunction()">clickme</button>
<textarea class="form-control" >something2</textarea>
<button onclick="myFunction()">clickme</button>
如何解决此问题以便复制多个文本区域?
要使用一个按钮从文本框中复制文本,您必须遍历所有文本框并复制其内容。您可以通过以下方式调整 JavaScript 函数来实现此目的;
function myFunction() {
// Get all textareas with class 'form-control'
var textAreas = document.getElementsByClassName("form-control");
// Loop through each textarea
for (var i = 0; i < textAreas.length; i++) {
var copyText = textAreas[i];
// Select the text field
copyText.select();
copyText.setSelectionRange(0, 99999); // For mobile devices
// Copy the text inside the text field
document.execCommand("copy");
// Optional: Alert the copied text for each textarea
alert("Copied the text: " + copyText.value);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Multiple Textareas</title>
</head>
<body>
<textarea class="form-control" tabindex="0">something</textarea>
<button onclick="myFunction()">Click me to copy all</button>
<textarea class="form-control" tabindex="3">something1</textarea>
<textarea class="form-control">something2</textarea>
</body>
</html>