1

すべての 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");
}
4

1 に答える 1

3

私があなたの質問を理解したら、あなたはこれが欲しいです:

Element.prototype.clickMe = function (func) {
    this.addEventListener('click', function () {
        func();
    });
};

デモンストレーション

しかし、ネイティブ オブジェクトのプロトタイプを変更することは、一般的に悪い習慣と見なされています。保守可能な JavaScriptを参照してください: 所有していないオブジェクトを変更しないでください

于 2013-10-09T11:38:21.527 に答える