javascript - 如何使用 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();
});
解决方案
一种方法是在复制内容之前从内容中删除换行符。
.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();
});
推荐阅读
- wordpress - 在所有设备上强制桌面视图 Wordpress
- apache - 如何通过脚本将自定义标头添加到 httpd?
- python - pytorch广播消耗的内存比扩展少吗?
- python - 比较两个整数而不使用任何比较(递归,python)
- c++ - 在 std::unordered_map 中移动插入/放置失败后恢复移动的元素
- python - 在块中迭代python中的字符串
- ada - 从 github 安装 ada 库——不断获取文件未找到错误
- python - Django 搜索只保存在本地
- c++ - 无效的迭代器:在不损失效率的情况下使用 UB 修复函数
- python - 你如何在 Python 3 的特定行中写一些东西?