2013-06-20 79 views
1

我正在使用Greasemonkey和JavaScript來修改頁面。我找到了所有的外部鏈接並在鏈接之前添加了一個圖像,我想在圖像上添加一個mouseover事件。我不知道如何在循環中做到這一點。這是我有:在Greasemonkey腳本的循環中添加圖像和mouseover事件?

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)); 
    } 
} 

回答

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 = ''; 
    } 
}