我在输入字段上触发绑定时将函数设置为未定义

I am getting function as undefined while i trigger a bind on input field

本文关键字:定时 函数 设置 未定义 绑定 输入 字段      更新时间:2023-09-26

我听到输入,当输入被更改时,我正在获取值。 作为初始,我将传递 1 作为默认值。 所以之后用户更改值我应该得到值,

但是我得到错误:undefined is not a function

问题是什么..?

这是我的代码:

var docLoader = function (params) {
    window.container = window.container || $("#tenderContent");
    return {
        init : function () {
            this.container = container.find("#documentscroll");
            this.inputPage = container.find("#inputpage");
            this.width = this.container.width();
            this.height = this.container.height();
            this.preload();
            this.inputChange();
            $(this.inputPage).bind("change paste keyup", this.inputChange);
        },
        preload : function () {
            var that = this;
            this.container.load("../common/preloader/index.html", 
                function(msg){
                $('#mask').css({width:that.width,height:that.height});
            });
        },
        //load page
        loadPage : function (num) {
            this.container.load("Doc/chapter"+num+"/index.html");
        },
        //input change
        inputChange : function (e) {
            var inputVal = e != undefined ? e.target.value : 1;
            this.loadPage(inputVal); //while page load it works, getting value from input, on change i am getting error.
        }
    }
}
jQuery(document).ready(function($) {
    docLoader().init();
    $(window).resize(function(){
        docLoader().init();
    });
});
在这个

函数(inputChange:)中,this引用当前($(this.inputPage))元素,这就是为什么你会得到错误(因为在元素中没有方法loadPage)。要修复它,您需要绑定this(这是对位于return {}中的object的引用)才能运行,有几种方法可以做到这一点

$(this.inputPage).bind("change paste keyup", this.inputChange.bind(this));

var _this = this;
$(this.inputPage).bind("change paste keyup", function (e) {
   _this.inputChange(e)
});

$(this.inputPage).bind("change paste keyup", $.proxy(this.inputChange, this));

关于 $.proxy