我正在使用Greasemonkey和JavaScript来修改页面。我找到了所有外部链接并在链接之前添加了图像,我想在图像上添加鼠标悬停事件。我不知道如何在循环中这样做。这就是我所拥有的:
var anchors = document.evaluate('//a[@target]',document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var icon4 = document.createElement('img');
icon4.src = '...';
for (var a = 0; a < anchors.snapshotLength; a++){
if (anchors.snapshotItem(a).href.substring(0,16) != location.href.substring(0,16)){
icon4.addEventListener('mouseover', function(){this.title = 'Hello'}, false);
icon4.addEventListener('mouseout', function(){this.title = ''}, false);
anchors.snapshotItem(a).parentNode.insertBefore(icon4.cloneNode(true),anchors.snapshotItem(a));
}
}
答案 0 :(得分:1)
不要在这样的循环中使用匿名函数。这会导致记忆和性能问题。
无论如何,请使用the return value of insertBefore()
。像这样:
var anchors = document.evaluate (
'//a[@target]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null
);
var icon4 = document.createElement('img');
icon4.src = '...';
for (var a = 0; a < anchors.snapshotLength; a++) {
if (anchors.snapshotItem(a).href.substring(0, 16) != location.href.substring(0, 16)) {
var newNode = anchors.snapshotItem(a).parentNode.insertBefore (
icon4.cloneNode (true), anchors.snapshotItem (a)
);
newNode.addEventListener ('mouseover', myMouseInOutHandler, false);
newNode.addEventListener ('mouseout', myMouseInOutHandler, false);
}
}
function myMouseInOutHandler (zEvent) {
if (zEvent.type == "mouseover") {
zEvent.target.title = 'Hello';
}
else if (zEvent.type == "mouseout") {
zEvent.target.title = '';
}
}