我知道这不是“最佳实践”,但我很好奇为什么这段代码不起作用。作为参考,我目前正在使用Chrome 63。
到处打字getElementById
是令人讨厌的。假设我有以下代码:
var D = document;
D.getID = D.getElementById;
D.getTags = D.getElementsByTags;
HTMLElement.prototype.getID = HTMLElement.prototype.getElementById;
HTMLElement.prototype.getTags = HTMLElement.prototype.getElementsByTags;
如果我尝试使用这些新名称,例如D.getID("foo").getID("bar")
,然后我得到错误D.getID("foo").getID("bar") is not a function
。这是怎么回事? (当然,D.getID("foo")
工作得很好)
由于ID在文档中应该是唯一的,因此没有HTMLElement.prototype.getElementById()
方法。拥有此方法的唯一对象是document
。
您可以通过指定绑定到HTMLElement
的函数将此方法添加到document
:
HTMLElement.prototype.getID = document.getElementById.bind(document);
请注意,即使您可以使用此方法从特定元素调用方法,它也将搜索整个文档,而不仅仅是在该元素中。您可以使用querySelector
来限制它:
HTMLElement.prototype.getID = function(id) {
return this.querySelector('#' + id);
}
您的getTags
代码只使用了long方法的错误名称。它应该是:
HTMLElement.prototype.getTags = HTMLElement.prototype.getElementsByTagName
由于D.getID
继承自D.getTags
,因此不需要对Document
和HTMLElement
进行任务。