javascript - 我无法在 javaScript 中选择和复制 onclick 事件“span 元素”
问题描述
select()
函数正在使用输入标签,但不适用于跨度标签。如何解决?
<span id="selector">paragraph<span>
<script>
document.getElementById("selector").addEventListner("click",
myFunction);
function myFunction(){
var selectItem = document.getElementById("selector");
selectItem.select();
document.execCommand("copy");
};
</script>
解决方案
可能,原因是正确使用select()函数不包括span标签,正如MDN网站所说:
“HTMLInputElement.select() 方法选择一个元素或包含文本字段的元素中的所有文本。”
在您的代码中正确使用如下:
<span id="selector1">paragraph<span>
<input id="to_select" type="text" name="text1" value="paragraph">
<input id="selector" type="button" value="Selector">
<script>
document.getElementById("selector").addEventListener("click",
myFunction);
function myFunction(){
var selectItem = document.getElementById("to_select");
selectItem.select();
document.execCommand("copy");
};
</script>
此外,@Jason Aller 的评论是正确的:“addEventListner 拼写不正确”
推荐阅读
- reactjs - 如何实施第三方脚本以使用提要填充页面?
- html - CSS Flex如何始终将孩子对齐到中心
- python-3.x - 为什么在一个简单的循环中,我使用 python 丢失了 sqlite3 表的 fetchAll 值?
- javascript - 错误:“绑定变量?未设置”...在雪花存储过程中多次绑定参数时,以下是我的存储过程
- php - 错误:无效路径 'public/C:\xampp\htdocs\oar-app-admin-api\storage\logs/laravel.log'
- javascript - 用 Jest 模拟 axios 和拦截器返回 mockImplementation undefined
- python - Raspberry Pi 相机在 OpenCV Python 程序的第二次执行时仅显示黑色图像
- ios - 为什么 gitignore 我的文件没有在 iOS 项目中添加?
- javascript - 如何在反应中删除 DOM 组件
- javascript - IndexedDb 列名