我想从html元素中复制一些内容的数据集。javascript副本与execCommand
HTML代码
<p id="[email protected]{{ id }}" data-password="@{{ password }}"
data-state="0">@{{ hidePassword }}</p>
<button class="mdl-button mdl-js-button mdl-button--icon">
<i data-event="copy" data-obj="util" data-target="[email protected]{{ id }}"
class="material-icons clickable-icon">content_copy</i>
</button>
复制方法
的方法beeing通过数据事件和数据OBJ属性调用。
copy (args) {
let copyText = document.getElementById(args.target).dataset.password;
console.log(copyTest); // output: specific password
document.execCommand("Copy");
}
像这样,它不会将内容复制到剪贴板。有人看到一个错误?
UPDATE
下面的代码工作的HTML元素的实际的textContent。
但我需要复制的数据密码属性
let range = document.createRange();
let selection = window.getSelection();
let node = document.getElementById(args.target);
range.selectNodeContents(node);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("copy");
可能的解决方法
所以我写了一个隐藏的输入字段中的值的值,选择它,将它复制并再次删除临时隐藏的输入字段。
但它没有复制任何东西。
let copyValue = document.getElementById(args.target).dataset.password;
document.body.insertAdjacentHTML('beforeend', `<input hidden id="temp-copy" value="${copyValue}">`);
let copyText = document.getElementById('temp-copy');
copyText.select();
document.execCommand("copy");
copyText.remove();
yeaa但据我所知,无法在p htmltag上调用select方法。我试过了,它会抛出一个错误copyText.select不是函数 –
@IlarioEngler在这种情况下 - https://stackoverflow.com/a/25456308/1401662 – vadim
谢谢我也发现了。但是文本在数据属性中 –