我有一系列 div,我向其中動態添加了一個增量 id。當我將滑鼠懸停在每個 div 上時,我還會出現一個提示,通知用戶他們可以復制文本
i=0;
$('.custom-text--result, .token').each(function(){
$(this).attr('id', 'copy-' i '');
$(this).append('<span onclick="copy(copy-' i ')">Copy</span>');
i ;
});
當我檢查代碼時,我的 div 上有我的 id,在工具提示的 onclick 中,我有相應的 id
<div class="token" id="copy-3">My text blablalba<span class="tooltiptext" onclick="copy(" #copy-3")"="">Copy text</span></div>
現在,如果我做類似的事情:
function copy(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
它不起作用..那么這里出了什么問題?我還在代碼中手動添加了id,它不起作用。
此外,我讀到 exec.commant 函式并不理想,最好使用剪貼板 API。我在 jquery 中找不到任何示例。我所有的代碼都在 jquery 中,我想在 jquery 中找到一個解決方案。
uj5u.com熱心網友回復:
我向您推薦一個純 JS 解決方案,因為剪貼板使用的是這樣的:
function copy(div) {
navigator.clipboard.writeText(div.innerText).then(
function() {
//if function work done work
alert('copy done by clipboard');
},
function() {
//if fail cliboard use execCommand
const inputTemp = document.createElement("input");
inputTemp.setAttribute("value", div.innerText);
document.body.appendChild(inputTemp);
inputTemp.select();
document.execCommand("copy");
document.body.removeChild(inputTemp);
alert('copy done by execCommand');
}
)
}
<div class="token" onclick="copy(this)">My text blablalbda</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/535440.html
標籤:查询剪贴板
