3

フォームセットで Django フォームを作成しようとしています。最後のフォームが何らかの入力を取得すると、そのフォームの最後に新しいフォームが自動的に追加されます。この js で入力検出を使用しています: http://whattheheadsaid.com/2010/09/effectively-detecting-user-input-in-javascript

ここにあるものは Firefox で問題なく動作し、addEventListener と removeEventListener をサポートする他のブラウザーを想定しています。detachEvent を IE フォールバックとして正しく設定する方法がわかりません。私はJavaScriptについてそれほど知識がなく、物事をまとめようとしているだけです。

jQuery.fn.cloneOnInput = function(prefix){
    return this.each(function() {
        var trElement = this
        var inputElements = $(this).find('input')
        var cloneForm = function() {
            cloneMore(trElement, prefix);
            inputElements.each(function(index) {
                if ("onpropertychange" in this) {
                    // What here?
                    }
                else {
                    this.removeEventListener("input", cloneForm);
                    }
                });
            };
        inputElements.each(function(index) {
            // Do I have to change the way it attaches?
            if ("onpropertychange" in this) { 
                this.attachEvent($.proxy(function () {
                if (event.propertyName == "value")
                    cloneForm();
                }, this));}
            else {
                this.addEventListener("input", cloneForm, false);
              }
        });

    });
};
4

1 に答える 1

1

後で削除するには、プロキシされたハンドラーを追跡する必要があります。ハンドラーは DOM 要素に関連付けられているため、data()を使用してこれを実現できます。

jQuery.fn.cloneOnInput = function(prefix) {
    return this.each(function() {
        var trElement = this;
        var inputElements = $(this).find("input");
        var cloneForm = function() {
            cloneMore(trElement, prefix);
            inputElements.each(function() {
                if ("onpropertychange" in this) {
                    this.detachEvent("onpropertychange",
                        $(this).data("proxiedHandler"));
                    $(this).removeData("proxiedHandler");
                } else {
                    this.removeEventListener("input", cloneForm);
                }
            });
        };
        inputElements.each(function(index) {
            // Do I have to change the way it attaches?
            if ("onpropertychange" in this) {
                var proxiedHandler = $.proxy(function() {
                    if (event.propertyName == "value") {
                        cloneForm();
                    }
                }, this);
                $(this).data("proxiedHandler", proxiedHandler);
                this.attachEvent("onpropertychange", proxiedHandler);
            } else {
                this.addEventListener("input", cloneForm, false);
            }
        });
    });
};
于 2012-05-27T12:28:17.083 に答える