我正在编写一个 Firefox 扩展,它将事件侦听器添加到页面上的所有锚标记。基本上我有:
window.addEventListener("load", function() { myExtension.init(); }, false);
var myExtension = {
init: function() {
var appcontent = document.getElementById("appcontent");
if(appcontent)
appcontent.addEventListener("DOMContentLoaded", myExtension.onPageLoad, true);
},
onPageLoad: function(event) {
var doc = event.originalTarget;
var anchors = doc.getElementsByTagName("a");
//attach event listeners
}
}
这适用于页面上的大多数标签。问题是使用 javascript 添加的标签没有附加事件侦听器。我试过重新定义createElement:
//in the onPageLoadFunction
var originalCreateElement = doc.createElement;
doc.createElement = function(tag) {
if (tag != "a"){
return originalCreateElement(tag);
}
var anchor = originalCreateElement("a");
anchor.addEventListener("mouseover", myInterestingFunction, false);
return anchor;
}
我已经尝试添加一个 DOM 插入侦听器
//in the onPageLoadFunction
function nodeInserted(event){;
addToChildren(event.originalTarget);
}
function addToChildren(node){
if (node.hasChildNodes()){
var nodes = node.childNodes;
for (var i = 0; i < nodes.length; i++){
addToChildren(nodes[i]);
}
}
if (node.nodeName == "a"){
anchorEvent(node); //adds event listeners to node
}
}
doc.addEventListener("DOMNodeInserted", nodeInserted, false);
但两者都不起作用。如何获取对这些锚对象的引用,以便向它们添加侦听器?
谢谢