首页 > 解决方案 > 如何使用 JavaScript 将文本复制到剪贴板而不使用换行符?

问题描述

我的网页中有一个表格。我编写了一个代码,用一个按钮将 td 文本复制到剪贴板。当我单击按钮 td 文本复制到带有断线的剪贴板时。如何在没有换行符的情况下复制 td 文本?

html代码:

<table>
                                
   <tr role="row">
      <th style="padding-right: 8px;">copy</th>
      <th style="padding-right: 8px;">phone</th>
   <tr/>

   <?php foreach ($all as $all_items) {?>
      <tr>
         <td>
         <button class="btn-copy" type="button" >copy</button>
         </td>

         <td>
             <?php if (isset($all_items['phone'])) echo $all_items['phone']; ?>
         </td>

      <tr/>
   <?php } ?>

</table>

我的 JavaScript 代码:

$(".btn-copy").click(function() {

    let tmpElement = $('<textarea style="opacity:0;"></textarea>');
    let parent = $(this).closest('td').siblings().not(':last').each(function(){
        tmpElement.text(tmpElement.text() + $(this).text() + '\t');            
    });
    
    tmpElement.appendTo($('body')).focus().select();
    document.execCommand("copy");
    tmpElement.remove();
});

标签: javascripthtmljquerycodeigniter

解决方案


一种方法是在复制内容之前从内容中删除换行符。

.replace(/(\r\n|\n|\r)/gm," ");

IE:

$(".btn-copy").click(function() {

    let tmpElement = $('<textarea style="opacity:0;"></textarea>');
    let parent = $(this).closest('td').siblings().not(':last').each(function(){
        tmpElement.text(tmpElement.text() + $(this).text() + '\t');    

        // Strip newlines
        tmpElement.text(tmpElement.text().replace(/(\r\n|\n|\r)/gm," "));        
    });
    
    tmpElement.appendTo($('body')).focus().select();
    document.execCommand("copy");
    tmpElement.remove();
});


推荐阅读