我想從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
謝謝我也發現了。但是文本在數據屬性中 –