我想保存到剪貼板一些文本添加dynamicaly在多個div
。保存到剪貼板的Javascript
目標:我有多個div(動態添加。可以是2或9999),並且想要一個按鈕(保存到剪貼板)爲每個textarea
。
var copyTextareaBtn = document.querySelector('.js-textareacopybtn');
copyTextareaBtn.addEventListener('click', function(event) {
var copyTextarea = document.querySelector('.js-copytextarea');
copyTextarea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
});
<div1>
<textarea class="js-copytextarea" style="width:100%;" rows="5">This is the text that will be selected. Note that you can hide this and implement a secret copy feature.</textarea>
<button class="js-textareacopybtn">Copy Textarea text</button>
</div1>
<div2>
<textarea class="js-copytextarea2" style="width:100%;" rows="5">This is the text that will be selected. Note that you can hide this and implement a secret copy feature.</textarea>
<button class="js-textareacopybtn2">Copy Textarea text</button>
</div2>
<div3>
<textarea class="js-copytextarea3" style="width:100%;" rows="5">This is the text that will be selected. Note that you can hide this and implement a secret copy feature.</textarea>
<button class="js-textareacopybtn3">Copy Textarea text</button>
</div3>
你使用jQuery真的嗎? –
這不是問題,那是你的目標。你對這個代碼具體有什麼問題?當你嘗試它會發生什麼? – JJJ
那麼,它會保存第一個textarea,而不是第二個,如果我點擊第二個按鈕。我知道這是一種正常的行爲,只是希望得到正確的幫助 – user1708580