Javascript - 复制一页上多个文本区域的文本按钮

Javascript - Copy Text buttons for multiple textareas on one page

我已经搜遍了本站的类似问题,但还是一头雾水。

基本上,我正在为一位离职的同事接手一个项目。他的 Intranet 页面计划应该有多个文本区域,每个文本区域都有自己的预定义文本和自己的 "copy text" 按钮。

点击后,它会复制到用户的剪贴板。我拆开了代码,无论出于何种原因,当我添加新的文本区域和按钮时,它都不会复制。第一个会。

我错过了什么或做错了什么?

<html>
<head>
    <script>
    window.onload = function () {
        var copyTextareaBtn = document.querySelector('.js-textareacopybtn');

        copyTextareaBtn.addEventListener('click', function (event) {
            var copyTextarea = document.querySelector('.js-copytextarea');
            copyTextarea.select();

            try {
                var successful = document.execCommand('copy');
                var msg = successful ? 'successful' : 'unsuccessful';
                console.log('Copying text command was ' + msg);
            } catch (err) {
                console.log('Whoops, unable to copy');
            }
        });
    }
    </script>
</head>
<body>
    <p>Test #1 </p>

    <div>
        <textarea class="js-copytextarea" readonly="readonly" style="width:20%;" 
        rows="5">Hello. This is textarea test bed #1</textarea>
        <button class="js-textareacopybtn">Copy Text (works)</button>

        <p>Test #2:</p>

        <textarea class="js-copytextarea" readonly="readonly" style="width:20%;" 
        rows="5">Hi! Welcome to textarea test bed #2 </textarea>
        <button class="js-textareacopybtn">Copy Text (broken)</button>
    </div>
</body>
</html>

它不起作用,因为您只将第一个按钮连接到单击事件,因为您只获得对第一个按钮的引用:

var copyTextareaBtn = document.querySelector('.js-textareacopybtn');

将其更改为:

var copyTextareaBtn = document.querySelectorAll('.js-textareacopybtn');

.querySelector() only returns a reference to the first element it finds that matches the selector. querySelectorAll() returns 包含所有匹配选择器的元素的节点列表。

接下来,您需要将点击事件附加到该节点列表中的每个元素,如果您将这些节点列表转换为数组,.forEach()方法使循环变得非常容易。

查看下面的更新代码:

window.onload = function () {
  // Get all the elements that match the selector as arrays
  var copyTextareaBtn = Array.prototype.slice.call(document.querySelectorAll('.js-textareacopybtn'));
  var copyTextarea = Array.prototype.slice.call(document.querySelectorAll('.js-copytextarea'));

  // Loop through the button array and set up event handlers for each element
  copyTextareaBtn.forEach(function(btn, idx){
  
    btn.addEventListener("click", function(){
    
      // Get the textarea who's index matches the index of the button
      copyTextarea[idx].select();

      try {
        var msg = document.execCommand('copy') ? 'successful' : 'unsuccessful';
        console.log('Copying text command was ' + msg);
      } catch (err) {
        console.log('Whoops, unable to copy');
      } 
      
    });
    
  });
}
<div>
  <p>Test #1 
    <textarea class="js-copytextarea" readonly="readonly" style="width:20%;" 
              rows="5">Hello. This is textarea test bed #1</textarea>
    <button class="js-textareacopybtn">Copy Text (works)</button>
  </p>

  <p>Test #2:
    <textarea class="js-copytextarea" readonly="readonly" style="width:20%;" 
              rows="5">Hi! Welcome to textarea test bed #2 </textarea>
    <button class="js-textareacopybtn">Copy Text (broken)</button>
  </p>
</div>

document.querySelectorAll() select 所有项目

<script>

window.onload = function () {

var copyTextareaBtn = document.querySelectorAll('.js-textareacopybtn');

copyTextareaBtn.forEach(function(btn){
btn.addEventListener('click', function (event) {
var copyTextarea = document.getElementById(this.dataset.txtid);
copyTextarea.select();

try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
alert('Copying text command was ' + msg);
} catch (err) {
alert('Whoops, unable to copy');
}
})});

</script>

</head>

<body>
<p>Test #1 </p>

<div>
<textarea id="txta1" class="js-copytextarea" readonly="readonly" style="width:20%;" 
rows="5">Hello. This is textarea test bed #1</textarea>
<button data-txtid="txta1" class="js-textareacopybtn">Copy Text (works)</button>

<p>Test #2:</p>

<textarea id="txta2" class="js-copytextarea" readonly="readonly" style="width:20%;" 
rows="5">Hi! Welcome to textarea test bed #2 </textarea>
<button data-txtid="txta2" class="js-textareacopybtn">Copy Text</button>

</div>

我用的是这种方式,比较好理解

1- 获取所有值并将其存储在 var 中。 2-创建文本区域并附加它。 3 - 将 var 值存储到 texterea。 4- 获取文本区域值。 5- 复制它:)

var form = document.getElementById('Note_form');
var title = document.getElementById('inpt_title');


// tool: Copy Note Form + Note Title .
function Copy_Note() {

    var copyTextarea = form.value+ title.value;

    var dummy = document.createElement("textarea");
    document.body.appendChild(dummy);
    dummy.value = copyTextarea;
    dummy.select();
    try {
        var msg = document.execCommand('copy') ? 'successful' : 'unsuccessful';
        console.log('Copying copyTextarea command was ' + msg);
    } catch (err) {
        console.log('Whoops, unable to copy');
    }

    document.body.removeChild(dummy);










}
                <!-- title -->
                <input type="text" id="inpt_title"  class="copy_erea" placeholder="The title.." maxlength="70" autofocus>
           
       
                <!-- the note -->
                <textarea id="Note_form" class="copy_erea" placeholder="The Content.." oninput="note_Edite(this.value);"></textarea>
          
                  <button id="copy_btn" onclick="Copy_Note();">copy</button>

这里也一样。我花了两天时间寻找这个答案,这个答案对我有用,在这里的另一个线程上找到了。

 <script>
    function CopyToClipboard(containerid) {
        if (window.getSelection) {
            if (window.getSelection().empty) { // Chrome
                window.getSelection().empty();
            } else if (window.getSelection().removeAllRanges) { // Firefox
                window.getSelection().removeAllRanges();
            }
        } else if (document.selection) { // IE?
            document.selection.empty();
        }
    
        if (document.selection) {
            var range = document.body.createTextRange();
            range.moveToElementText(document.getElementById(containerid));
            range.select().createTextRange();
            document.execCommand("copy");
        } else if (window.getSelection) {
            var range = document.createRange();
            range.selectNode(document.getElementById(containerid));
            window.getSelection().addRange(range);
            document.execCommand("copy");
        }
    }</script>


      <button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>
    <div id="div1">Text To Copy </div>