javascript - 当我触发输入字段上的绑定(bind)时,我得到的函数为未定义

标签 javascript jquery

我听到了一个输入,当输入改变时我得到了值(value)。作为初始值,我传递 1 作为默认值。所以在用户更改值之后我应该得到这些值,

但我收到错误:未定义不是函数

问题出在哪里..?

这是我的代码:

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)) 元素的引用,这就是为什么你会得到错误(因为在 element 中没有方法 loadPage)。要修复它,您需要绑定(bind) 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

关于javascript - 当我触发输入字段上的绑定(bind)时,我得到的函数为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27639323/

相关文章:

javascript - 使用 jquery 恢复函数

javascript - 如何在 angular.js 中使用 $http 创建同步?

javascript - 在jquery mobile中每3秒执行一个函数

javascript - 我如何编写一个适用于 mousemove 事件的函数并在文档就绪时调用它?

javascript - NextJS - 在 getStaticProps 中获取动态变量

javascript - Angular 变化集中于 react 形式的输入

javascript - Node.js 请求模块获取现代版本的网站

javascript - 由javascript函数生成的自动增量li标签

jquery - jqGrid:无法获取子网格中的数据

javascript - 如何在tinyMCE中添加项目符号和数字列表键盘快捷键?