Dag*_*bit 4 javascript cross-browser getelementsbyclassname
更新标题以更好地反映我正在尝试做的事情.
简而言之,不同的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(){
/* ... */
}
/* ... */
});
Run Code Online (Sandbox Code Playgroud)
当然,我想在没有列出每个单独的html元素的情况下这样做.谁能想到更好的方法?
(原始问题如下)
目标-使getElementsByClassName任何一种浏览器的DOM节点上的工作.
它已经完成了(有点),但这是我的镜头.
我的问题是,有一个很好的方法来使用动态创建的元素吗?似乎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);
}
}
}());
Run Code Online (Sandbox Code Playgroud)
它适用于加载脚本之前加载的内容,但新动态创建的元素不会获得getElementsByClassName方法.有任何建议(除了setInterval,请)?
我认为你想要的东西可以通过Element界面原型来实现,比如
Element.prototype.getElementsByClassName = function() {
/* do some magic stuff */
};
Run Code Online (Sandbox Code Playgroud)
但不要这样做.它在所有主流浏览器中都无法可靠地运行.
您在问题中的示例中所做的事情也是不可取的.您实际上正在扩展主机对象.再说一遍,请不要这样做.
你将陷入Prototype遇到的那些陷阱.
我不想仅仅复制Kangax的文章,所以请阅读扩展DOM有什么问题.
你为什么一开始想要这个?你的目标是什么?
| 归档时间: |
|
| 查看次数: |
1573 次 |
| 最近记录: |