了解更改事件中jQuery中'this'的范围

And*_*ton 4 javascript jquery scope

我为我正在研究的项目编写了一个jQuery的快速自定义扩展.我很难理解我希望实现的自定义onChange方法中'this'的范围.如果省略我的代码中间我调用webservice,但如果你检查最后两个方法,你会看到我的问题所在.我想用所选的值更改调用updateDetails方法.但是,当在onchange事件中调用该方法时,我显然会失去"this"的范围,因为this.materialListResponse在此上下文中返回为undefined.任何帮助我理解这一点的帮助将不胜感激.

$.fn.appendMaterials = function (options) {

       this.options = options;

       //Set Default Options

       this.defaults = {

           typeID: '66E1320D-51F9-4900-BE84-6D5B571F9B80'

       };

       this.options = $.extend({}, this.defaults, options);

       //
       Code here to call web service and generate response XML
       //

       this.materialListResponse = $.xml2json(

       $.parseXML($(this.materialListWebservice()).find("GetMaterialTreeResponse").text())).Materials.Material;

       this.appendOptionString = function () {
           var i = 0;
           this.optionString = '<option>'
           for (i = 0; i < this.materialListResponse.length; i++) {
               this.optionString += '<option>' + this.materialListResponse[i].MaterialCode + '</option>';
           };

           this.append(this.optionString);

           return this;
       };

       this.appendOptionString();

       this.updateDetails = function () {
           for (i = 0; i < this.materialListResponse.length; i++) {

               if (this.materialListResponse[i].MaterialCode === this.val()) {

                   $('#table1 #MaterialDescription').val(this.materialListResponse[i].Description);

               }
           }
       }

       this.change(this.updateDetails)

   };    
Run Code Online (Sandbox Code Playgroud)

nic*_*son 5

将对象this作为数据传递给事件:

this.change({that: this}, this.updateDetails)
Run Code Online (Sandbox Code Playgroud)

然后您可以that在事件回调范围内访问

this.updateDetails = function(event) {
    var that = event.data.that;
    ...
}
Run Code Online (Sandbox Code Playgroud)

资源

  • 你应该在事件处理程序中声明`that`变量,否则它将是全局的. (3认同)