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 回答