Skip to main content
 首页 » 编程设计

jquery之单击 anchor 标记时将其链接复制到剪贴板

2026年07月28日6birdshome

这是我用来显示一些数据的代码。在此代码中,我有 anchor 标记,我想在单击该 anchor 标记时复制该 anchor 标记的链接。这是我使用的代码,如下所示:

<div class="search_item_list clearfix" id="response"> 
   <?php foreach($jobs as $job){ 
   ?> 
    <a class="copy_text"  data-toggle="tooltip" title="Copy to Clipboard"  
       href="<?=base_url().'home/company_profile_detail?id='.$job['company_id'];?>"><span class="icon link"><i class="fa fa-link"></i></span>Copy Link</a> 
    <?php } ?> 
</div> 
 
<script> 
   $(".copy_text").click(function(e){ 
      e.preventDefault(); 
      var button = $(this); 
      var text = button.attr("href"); 
      text.select(); 
      $(document).execCommand("copy"); 
      alert("Copied the text "); 
   }) 
</script> 

我得到的 jQuery 为

text.select is not a function.

请您参考如下方法:

尝试下面的代码片段

$('.copy_text').click(function (e) { 
   e.preventDefault(); 
   var copyText = $(this).attr('href'); 
 
   document.addEventListener('copy', function(e) { 
      e.clipboardData.setData('text/plain', copyText); 
      e.preventDefault(); 
   }, true); 
 
   document.execCommand('copy');   
   console.log('copied text : ', copyText); 
   alert('copied text: ' + copyText);  
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
 <a class="copy_text"  data-toggle="tooltip" title="Copy to Clipboard" href="home/company_profile_detail">Copy Link</a>