将 html 从多个<pre>标签复制到剪贴板



我在[pre]标签中有几段HTML,我想将它们与类'bla'的复制按钮关联起来。我的JS代码下面的工作为一个[pre id="copyCodeOne"]但我需要独立复制几个…so [pre id="copyCodeTwo"];[pre id="copyCodeThree"]等。我需要改变我的JS下面请吗?

提前感谢。

// HTML
<code>
<pre id="copyCodeOne">
any html here
</pre>
</code>
// END HTML
// JS
var bttn = document.getElementsByClassName("bla");
for(var i = 0; i < bttn.length; i++) {
bttn[i].addEventListener('click', copyFunction, true);
}
// Copy code to clipboard
function copyFunction() {
const copyText = document.getElementById("copyCodeOne").textContent; // >>> I need several of these
const textArea = document.createElement('textarea');
textArea.textContent = copyText;
document.body.append(textArea);
textArea.select();
document.execCommand("copy");
};
// END JS

Select by index

使用按钮的索引来选择你的预元素,像这样:

<pre>
any html here
</pre>
function addListeners() {
const btns = document.getElementsByClassName("bla");
for(var i = 0; i < btn.length; i++) {
btns[i].addEventListener('click', (e) => copyFunction(i), true); // call function with idx 
}
}

function copyFunction(idx) {
// use idx to select right 'pre' tag
const copyText = document.querySelectorAll('pre')[idx].textContent;
const textArea = document.createElement('textarea');
textArea.textContent = copyText;
document.body.append(textArea);
textArea.select();
document.execCommand("copy");
};

这是一个工作的Stackblitz。

注意:如果你得到'cannot read textContent of undefined',这可能意味着你的'pre'元素不存在,或者你有比按钮更多的pre元素。

欢呼

最新更新