Javascript 通过单击文本和按钮进行复制
我可以在点击表格单元格后立即复制文本,但在点击按钮后无法复制文本。有什么办法可以解决这种问题吗。我认为问题可能出在js的这一行Javascript 通过单击文本和按钮进行复制,javascript,html,jquery,css,Javascript,Html,Jquery,Css,我可以在点击表格单元格后立即复制文本,但在点击按钮后无法复制文本。有什么办法可以解决这种问题吗。我认为问题可能出在js的这一行constel=document.createElement('textarea')但我不确定。 /*单击文本后复制*/ document.queryselectoral(“.table cell”).forEach(函数(elm){ elm.addEventListener(“单击”,函数(e){ e、 target.style.backgroundColor='绿
constel=document.createElement('textarea')代码>但我不确定。
/*单击文本后复制*/
document.queryselectoral(“.table cell”).forEach(函数(elm){
elm.addEventListener(“单击”,函数(e){
e、 target.style.backgroundColor='绿色';
var copyText=e.target.textContent;
const el=document.createElement('textarea');
el.value=复制文本;
文件.正文.附件(el);
el.select();
document.execCommand('copy');
文件.正文.删除文件(el);
/*警告复制的文本*/
警报(“复制文本:+el.value”);
});
})
函数myFunction(){
/*获取文本字段*/
var copyText=document.getElementById(“myInput”);
/*选择文本字段*/
copyText.select();
copyText.setSelectionRange(0,99999);/*用于移动设备*/
/*复制文本字段内的文本*/
文件。执行命令(“副本”);
/*警告复制的文本*/
警报(“复制的文本:+copyText.value”);
}
td按钮{
浮动:对;
}
td按钮:之前{
内容:“复制”;
}
弗斯特
最后
手柄
卡钦
奥托
@mdo
雅各布
桑顿
@肥
拉里
鸟
@推特
发生这种情况的原因是,当您单击按钮时,您试图复制它自己的文本而不是表格单元格
elm.addEventListener(“单击”,函数(e){
e、 target.style.backgroundColor='绿色';
var copyText=e.target.textContent;//单击按钮时,“e”是按钮
...
}
既然按钮是的子按钮,那么让按钮不做任何事情,让点击事件传播到,让它的侦听器处理所有事情怎么样
document.queryselectoral(“.table cell”).forEach(函数(elm){
elm.addEventListener(“单击”,copyText);
})
函数copyText(e){
常数td=e.currentTarget;
td.style.backgroundColor='绿色';
var copyText=td.textContent;
const el=document.createElement('textarea');
el.value=复制文本;
文件.正文.附件(el);
el.select();
document.execCommand('copy');
文件.正文.删除文件(el);
/*警告复制的文本*/
警报(“复制文本:+el.value”);
}
td按钮{
浮动:对;
}
td按钮:之前{
内容:“复制”;
}
弗斯特
最后
手柄
卡钦
奥托
@mdo
雅各布
桑顿
@肥
拉里
鸟
@推特
我提出了一种不同的方法来解决您手头的问题。我所做的是删除直接调用onclick=“myFunction()”
并在eventListener
中实现标记验证,以检查元素是否是按钮,然后不再调用myFunction()
,现在已经被弃用了,我只是在那里收集了值。作为回报,这也避免了重复的代码行
/*单击文本后复制*/
document.queryselectoral(“.table cell”).forEach(函数(elm){
elm.addEventListener(“单击”,函数(e){
var-copyText;
如果(e.target.tagName==“BUTTON”){/这就是错误的原因
elm.addEventListener(“单击”,函数(e){
e、 target.style.backgroundColor='绿色';
var copyText=e.target.textContent;//单击按钮时,“e”是按钮
...
}