我正在编写一个脚本,该脚本将创建一个附加按钮“心脏”,以将链接复制到剪贴板。
var AllReferenceNode = document.getElementsByClassName('rowid-link');
for (var i = 0; i < AllReferenceNode.length; i++) {
var XnewNode = document.createElement('a');
XnewNode.innerHTML = "<span class='icon fa fa-heart'></span>";
XnewNode.id = AllReferenceNode[i].getAttribute("href");
XnewNode.className = "QKCopyLink";
XnewNode.href = "javascript:void(0);";
AllReferenceNode[i].after(XnewNode);
}
var Links = document.getElementsByClassName('QKCopyLink');
for (var i = 0; i < Links.length; i++) {
//console.log(i);
var href = document.getElementsByClassName('rowid-link')[i].getAttribute("href");
//console.log(dupa);
//console.log(document.getElementById(dupa));
document.getElementById(href).addEventListener('click', function(){
var dummy = document.createElement('input');
//var copyText = document.getElementsByClassName("rowid-link").getAttribute("href");
document.body.appendChild(dummy);
dummy.value = href;
dummy.select();
document.execCommand('copy');
document.body.removeChild(dummy);
});
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<h6 class="history-title">Sat, 2019-11-16, 03:52
| Notes
|
<span class="username">USER</span>
<a href="#1-2LS7J5O" class="rowid-link">
<span class="icon bookmark fa fa-cloud"></span></a>
<span class="history-reply">
[<a href="#" class="activity-reply">reply</a>]
</span>
</h6>
<h6 class="history-title">Sat, 2019-11-16, 03:52
| Notes
|
<span class="username">USER</span>
<a href="#1-2LS7v5O" class="rowid-link">
<span class="icon bookmark fa fa-cloud"></span></a>
<span class="history-reply">
[<a href="#" class="activity-reply">reply</a>]
</span>
</h6>
<h6 class="history-title">Sat, 2019-11-16, 03:52
| Notes
|
<span class="username">USER</span>
<a href="#1-2LS7JdO" class="rowid-link">
<span class="icon bookmark fa fa-cloud"></span></a>
<span class="history-reply">
[<a href="#" class="activity-reply">reply</a>]
</span>
</h6>
<h6 class="history-title">Sat, 2019-11-16, 03:52
| Notes
|
<span class="username">USER</span>
<a href="#1-2LS7JaO" class="rowid-link">
<span class="icon bookmark fa fa-cloud"></span></a>
<span class="history-reply">
[<a href="#" class="activity-reply">reply</a>]
</span>
</h6>
问题是循环的最后一次运行将覆盖所有事件-所有“心”都复制了最后一个相同的链接。看来事件已被覆盖,但由于我将元素设置在哪个事件侦听器上,因此不确定该怎么做:
document.getElementById(href).addEventListener('click', function(){...
请向我解释为什么会这样。
答案 0 :(得分:0)
更改:
dummy.value = href;
对此:
dummy.value = this.id;
解决了该问题。