Javascript - 复制一个页面上的多个textareas的文本按钮 [英] Javascript - Copy Text buttons for multiple textareas on one page

查看:90
本文介绍了Javascript - 复制一个页面上的多个textareas的文本按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜遍了这个网站的类似问题,但我仍然处于亏损状态。

基本上,我正在接管一个正在进行的同事的项目。他的内联网页面应该有多个textareas,每个textareas都有自己的预定义文本和他们自己的复制文本按钮。



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



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

 < 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();

尝试{
var success = document.execCommand('copy');
var msg =成功?'成功':'不成功';
console.log ('复制文本命令为'+ msg);
} catch(err){
console.log('Whoop,无法复制');
}
});
}
< / script>
< / head>
< body>
< p> Test#1< / p>

< div>
< textarea class =js-copytextareareadonly =readonlystyle =width:20%;
rows =5>您好。这是textarea测试台#1< / textarea>
< button class =js-textareacopybtn>复制文字(作品)< /按钮>

< p>测试#2:< / p>

< textarea class =js-copytextareareadonly =readonlystyle =width:20%;
rows =5>嗨!欢迎来到textarea测试床#2< / textarea>
< button class =js-textareacopybtn>复制文字(破碎)< /按钮>
< / div>
< / body>
< / html>


解决方案

这不起作用,因为您只是连接第一个按钮因为您只是获取对第一个按钮的引用:

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

将其更改为:

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

.querySelector() 仅返回对第一个它找到与选择器匹配的元素。 querySelectorAll() code> 返回一个节点列表,其中包含与选择器匹配的所有元素。



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

代码如下:

window.onload = function(){// Get all与数组选择符匹配的元素var copyTextareaBtn = Array.prototype.slice.call(document.querySelectorAll('的.js-textareacopybtn)); var copyTextarea = Array.prototype.slice.call(document.querySelectorAll('。js-copytextarea')); //循环访问按钮数组并为每个元素设置事件处理函数copyTextareaBtn.forEach(function(btn,idx){btn.addEventListener(click,function(){//获取textarea的索引值与按钮copyTextarea [idx] .select();尝试{var msg = document.execCommand('copy')?'成功':'不成功'; console.log('复制文本命令为'+ msg);} catch(err ){console.log('Whoops,could not copy');}});});}

 < DIV> < p> Test#1< textarea class =js-copytextareareadonly =readonlystyle =width:20%;行= 5 >你好。这是textarea测试台#1< / textarea> < button class =js-textareacopybtn>复制文字(作品)< /按钮> < / p为H. < p>测试#2:< textarea class =js-copytextareareadonly =readonlystyle =width:20%;行= 5 >嗨!欢迎来到textarea测试床#2< / textarea> < button class =js-textareacopybtn>复制文字(破碎)< /按钮> < / div>  


I have scoured this site's similar questions, but I'm still at a loss.

Basically, I'm taking over a project for a co-worker who is moving on. His plans for an intranet page is supposed to have multiple textareas each with its own predefined text and their own "copy text" button.

On click, it copies to the user's clipboard. I pulled apart the code and for whatever reason, when I add new textareas and a button, it will not copy. The first one will.

What am I missing or doing wrong?

<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>

解决方案

It's not working because you are only hooking the first button up to a click event because you are only getting a reference to the first button:

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

Change that to:

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

.querySelector() only returns a reference to the first element it finds that matches the selector. querySelectorAll() returns a node list that contains all elements that match the selector.

Next, you'll need to attach the click event to each element within that node list and, if you convert those node lists to Arrays, the .forEach() method makes looping very easy.

See the updated code below:

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>

这篇关于Javascript - 复制一个页面上的多个textareas的文本按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆