我不了解JavaScript,但我设法使用来自各种Stack Overflow答案的位和代码将这些代码放在一起.它工作正常,它通过警告框输出文档中所有选中复选框的数组.
function getSelectedCheckboxes(chkboxName) {
var checkbx = [];
var chkboxes = document.getElementsByName(chkboxName);
var nr_chkboxes = chkboxes.length;
for(var i=0; i<nr_chkboxes; i++) {
if(chkboxes[i].type == 'checkbox' && chkboxes[i].checked == true) checkbx.push(chkboxes[i].value);
}
return checkbx;
}
Run Code Online (Sandbox Code Playgroud)
我称之为:
<button id="btn_test" type="button" >Check</button>
<script>
document.getElementById('btn_test').onclick = function() {
var checkedBoxes = getSelectedCheckboxes("my_id");
alert(checkedBoxes);
}
</script>
Run Code Online (Sandbox Code Playgroud)
现在我想修改它,所以当我单击btn_test按钮时,输出数组checkbx被复制到剪贴板.我尝试添加:
checkbx = document.execCommand("copy");
Run Code Online (Sandbox Code Playgroud)
要么
checkbx.execCommand("copy");
Run Code Online (Sandbox Code Playgroud)
在函数的最后,然后调用它:
<button id="btn_test" type="button" onclick="getSelectedCheckboxes('my_id')">Check</button>
Run Code Online (Sandbox Code Playgroud)
但它不起作用.没有数据复制到剪贴板.
我有这段代码可以工作:
let textarea = document.createElement('textarea');
textarea.setAttribute('type', 'hidden');
textarea.textContent = 'the string you want to copy';
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
Run Code Online (Sandbox Code Playgroud)
如您所见-我要复制字符串。但是我必须创建一个临时的隐藏DOM元素以在复制到剪贴板之前对字符串进行评分。
我的问题是,是否有一些API可以完全不需要DOM复制到剪贴板?像这样的东西:
document.execCommand('copy', 'the string data to put in clipboard');
Run Code Online (Sandbox Code Playgroud)
似乎很奇怪DOM是必要的。另外,请注意,这个剪贴板API非常奇怪,还有其他人同意吗?