如何将我自己的方法添加到 HTMLElement 对象? [英] How to add my own methods to HTMLElement object?
问题描述
例如对于 this.parentNode
我只想写 this.p
或代替document.getElementById('someid')
只需编写 document.g('someid')
.当然这些都是简单的例子,我只是想知道正确的做法是什么.
For example for this.parentNode
I would like to just write this.p
or instead of
document.getElementById('someid')
just write document.g('someid')
. Of course that are simple examples, I just want to know what is the correct way to do it.
(我知道我可以使用 jQuery 或 Prototype,但我想了解它是如何在 JS 中真正完成的)
(I know I can use jQuery or Prototype, but I'd like to learn how it is really done in JS)
推荐答案
虽然您可以在许多浏览器中的 HTMLElement
上建立原型 - Internet Explorer (6,7,8) 是不是其中之一.AFAIK,IE9 确实支持这个(虽然我还没有测试过).
Although you can prototype on the HTMLElement
in many browsers - Internet Explorer (6,7,8) is NOT one of them. AFAIK, IE9 does support this (though I haven't tested it).
对于处理它的浏览器,你可以这样做:
For browsers that do handle it, you can do:
HTMLElement.prototype.doHello = function(thing){
console.log(this + ' says: ' + thing)
}
document.body.doHello('hello')
这篇关于如何将我自己的方法添加到 HTMLElement 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!