单击Jquery中的按钮时,从本地存储中复制字符串



当我点击按钮时,我想复制字符串,而text.select((函数对字符串无效。

有人能告诉我怎么做吗

//getting the text from local storage
let text = window.localStorage.getItem('content');//return string
//select the text
text.select();//this give the error because this only accept the HTML collection
//range
text.setSelectionRange(0, 999999999);
//copy command
document.execCommand("copy");

使用剪贴板API:

const text = window.localStorage.getItem('content');
navigator.clipboard.writeText(text).then(function() {
/* clipboard successfully set */
}, function() {
/* clipboard write failed */
});

以下是如何将整个localStorage复制为JSON字符串

async function copyJson() {
try {
await navigator.clipboard.writeText(
JSON.stringify(localStorage)
);
console.log('Content copied to clipboard');
/* Resolved - text copied to clipboard successfully */
} catch (err) {
console.error('Failed to copy: ', err);
/* Rejected - text failed to copy to the clipboard */
}
}

要使该功能在单击时工作,请将onclick="copyJson()"添加到HTML 中的按钮属性

最新更新