我已经搜索过该网站的类似问题,但我仍然不知所措。
基本上,我正在为一位即将离职的同事接手一个项目。他的 Intranet 页面计划应该有多个文本区域,每个文本区域都有自己的预定义文本和自己的“复制文本”按钮。
单击时,它会复制到用户的剪贴板。我拆开了代码,无论出于何种原因,当我添加新的文本区域和按钮时,它都不会复制。第一个会的。
我错过了什么或做错了什么?
<html>
<head>
<script>
window.onload = function () {
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('Whoops, unable to copy');
}
});
}
</script>
</head>
<body>
<p>Test #1 </p>
<div>
<textarea class="js-copytextarea" readonly="readonly" style="width:20%;"
rows="5">Hello. This is textarea test bed #1</textarea>
<button class="js-textareacopybtn">Copy Text (works)</button>
<p>Test #2:</p>
<textarea class="js-copytextarea" readonly="readonly" style="width:20%;"
rows="5">Hi! Welcome to textarea test bed #2 </textarea>
<button class="js-textareacopybtn">Copy Text (broken)</button>
</div>
</body>
</html>
它不起作用,因为您仅将第一个按钮连接到单击事件,因为您仅获得对第一个按钮的引用:
var copyTextareaBtn = document.querySelector('.js-textareacopybtn');
将其更改为:
var copyTextareaBtn = document.querySelectorAll('.js-textareacopybtn');
.querySelector() https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector只返回对它找到的与选择器匹配的第一个元素的引用。querySelectorAll() https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll返回一个节点列表,其中包含与选择器匹配的所有元素。
接下来,您需要将单击事件附加到该节点列表中的每个元素,如果将这些节点列表转换为数组,则.forEach() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach方法使循环变得非常容易。
请参阅下面更新的代码:
window.onload = function () {
// Get all the elements that match the selector as arrays
var copyTextareaBtn = Array.prototype.slice.call(document.querySelectorAll('.js-textareacopybtn'));
var copyTextarea = Array.prototype.slice.call(document.querySelectorAll('.js-copytextarea'));
// Loop through the button array and set up event handlers for each element
copyTextareaBtn.forEach(function(btn, idx){
btn.addEventListener("click", function(){
// Get the textarea who's index matches the index of the button
copyTextarea[idx].select();
try {
var msg = document.execCommand('copy') ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Whoops, unable to copy');
}
});
});
}
<div>
<p>Test #1
<textarea class="js-copytextarea" readonly="readonly" style="width:20%;"
rows="5">Hello. This is textarea test bed #1</textarea>
<button class="js-textareacopybtn">Copy Text (works)</button>
</p>
<p>Test #2:
<textarea class="js-copytextarea" readonly="readonly" style="width:20%;"
rows="5">Hi! Welcome to textarea test bed #2 </textarea>
<button class="js-textareacopybtn">Copy Text (broken)</button>
</p>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)