许多不同的链接可以复制

Many different links to copy

var ShortCut = document.querySelector('.Copy_Link');
ShortCut.addEventListener('click', function(event)
{
    var ShortCut = document.querySelector('.Copy_Container');
    ShortCut.focus();
    ShortCut.select();
try
{
    var successful = document.execCommand('copy');
    var msg = successful? 'successful': 'unsuccessful';
    console.log('Copying the shortcut is ' + msg);
}
catch (err)
{
    console.log('Unsuccessful copying.');
}
});

这是一个从隐藏文本区复制一个link的脚本。我想在同一页上有几个单独的 link,但是这个脚本:

var ShortCut = document.querySelectorAll('.Copy_Link1, .Copy_Link2, .Copy_Link3');
ShortCut.addEventListener('click', function(event)
{
    var ShortCut = document.querySelectorAll('.Copy_Container1, .Copy_Container2, .Copy_Container3');
    ShortCut.focus();
    ShortCut.select();
try
{
    var successful = document.execCommand('copy');
    var msg = successful? 'successful': 'unsuccessful';
    console.log('Copying the shortcut is ' + msg);
}
catch (err)
{
    console.log('Unsuccessful copying.');
}
});

失败。

链接:

<SPAN class="Copy_Link1">Copy the shortcut link 1</SPAN>
<TEXTAREA class="Copy_Container1" Hidden ReadOnly>
TEXT FOR COPYING INTO CLIPBOARD 1
</TEXTAREA>

<SPAN class="Copy_Link2">Copy the shortcut link 2</SPAN>
<TEXTAREA class="Copy_Container2" Hidden ReadOnly>
TEXT FOR COPYING INTO CLIPBOARD 2
</TEXTAREA>

<SPAN class="Copy_Link3">Copy the shortcut link 3</SPAN>
<TEXTAREA class="Copy_Container3" Hidden ReadOnly>
TEXT FOR COPYING INTO CLIPBOARD 3
</TEXTAREA>

希望你明白我想要什么。我什至找不到适用于我的特定情况的类似解决方案,我尝试了几种方法,但只有这个有效。有什么不明白的地方欢迎追问。

您可以在 span 上放置一个数据元素,以告诉它 select 到哪个文本区域。

$('.Copy_Link').on('click', function(e){
  var target = document.getElementById(this.dataset.target);
  
  target.focus();
  target.select();
  
  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying the shortcut is ' + msg);
  } catch (err) {
    console.log('Unsuccessful copying.');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<SPAN class="Copy_Link" data-target="Copy_Container1">Copy the shortcut link 1</SPAN>
<TEXTAREA id="Copy_Container1" Hidden ReadOnly>
TEXT FOR COPYING INTO CLIPBOARD 1
</TEXTAREA>

<SPAN class="Copy_Link" data-target="Copy_Container2">Copy the shortcut link 2</SPAN>
<TEXTAREA id="Copy_Container2" Hidden ReadOnly>
TEXT FOR COPYING INTO CLIPBOARD 2
</TEXTAREA>

<SPAN class="Copy_Link" data-target="Copy_Container3">Copy the shortcut link 3</SPAN>
<TEXTAREA id="Copy_Container3" Hidden ReadOnly>
TEXT FOR COPYING INTO CLIPBOARD 3
</TEXTAREA>