我想为每个DOM元素添加一些函数,但我不想遍历所有元素。这是演示代码:
window.onload = function () {
/* get the constructor of document, which is Document
add the clickMe function to the prototype */
document.constructor.prototype.clickMe = function (func) {
this.addEventListener('click', function () {
func();
});
};
document.clickMe(clickDocument); // works
/* doesn't work, because the prototype of document.getElementById('random_btn')
does not have the function clickMe (makes sense) */
document.getElementById('random_btn').clickMe(clickRandomBtn);
}
function clickDocument() {
alert("clicked documet");
}
function clickRandomBtn() {
alert("clicked a random button");
}
答案 0 :(得分:3)
如果我理解你的问题,你想要这个:
Element.prototype.clickMe = function (func) {
this.addEventListener('click', function () {
func();
});
};
但是改变原生对象的原型通常被认为是一种不好的做法。见Maintainable JavaScript: Don’t modify objects you don’t own