更新後的標題更好地反映了我正在嘗試做的事情。修改每個可能的DOM元素的原型
簡而言之,不同的dom元素有不同的構造函數,它們似乎並不共享一個通用的原型。我正在尋找一種方法來通過修改這些原型來爲每個DOM元素添加一個函數屬性,但我不知道如何找到它們。
例如,我可以做這樣的事情:
function enhanceDom (tagNames, methods) {
var i=-1, tagName;
while (tagName=tagNames[++i]) {
var tag=document.createElement(tagName);
if (!(tag && tag.constructor)) continue;
for (var methodName in methods) {
tag.constructor.prototype[methodName]=methods[methodName];
}
}
}
var thingsToEnhance = ['a','abbr','acronym','address'/* on and on... */];
enhance(thingsToEnhance, {
doStuff : function(){
/* ... */
},
doOtherStuff : function(){
/* ... */
}
/* ... */
});
當然,我想這樣做沒有列出每一個html元素。任何人都可以想出更好的方法嗎?
(原題如下)
目標 -使任何一種瀏覽器的DOM節點上getElementsByClassName
工作。
它已經完成之前(有點),但這是我的拍攝。
我現在的問題是,有沒有一種很好的方式使這個工作與動態創建的元素?看來,HTML DOM元素不共享可以添加getElementsByClassName
的通用可預測原型......或者我錯過了什麼?
這是我到目前爲止(編輯 - 更新每討論)。
(function(){
var fn = 'getElementsByClassName';
// var fn = 'gEBCN'; // test
if (typeof document[fn] != 'undefined') return;
// This is the part I want to get rid of...
// Can I add getByClass to a single prototype
// somewhere below Object and be done with it?
document[fn]=getByClass;
withDescendants(document, function (node) {
node[fn]=getByClass;
});
function withDescendants (node, callback, userdata) {
var nodes = node.getElementsByTagName('*'), i=-1;
while (node=nodes[++i]) {
callback(node, userdata);
}
return userdata;
}
function getByClass (className) {
return withDescendants(this, getMatches, {
query:new RegExp('(^|\\s+)' + className + '($|\\s+)'),
found:[]
}).found;
}
function getMatches (node, data) {
if (node.className && node.className.match(data.query)) {
data.found.push(node);
}
}
}());
它運作良好的腳本加載之前加載的內容,但新的動態創建的元素不會得到一個getElementsByClassName
方法。任何建議(除了setInterval,請)?
是否有某些原因決定不使用jQuery這樣的框架?如果是這樣,你可能想在你的問題中聲明,否則你會得到很多「使用jQuery!」答案。 – 2010-09-06 19:19:16
我希望很明顯,我不打算爲此使用jQuery。手指交叉。 – 2010-09-06 19:21:24
@Greg在發佈的代碼中沒有JQuery代碼,並且沒有JQuery標記,我認爲就足夠了... – 2010-09-06 19:22:41