1

我想<select>在我的object. 我想为所有这些使用原型模式,我不得不承认我对模式很陌生。这是我所拥有的:

HTML 示例:

<select id="ddFullName" name="Full_Name" ></select>

XML 示例:

<names>
  <nameDetails name="Name 01" phone="555-867-5309" email="none@nothing.no" />
  <nameDetails name="Name 02" phone="555-867-5309" email="none@nothing.no" />
  <nameDetails name="Name 03" phone="555-867-5309" email="none@nothing.no" />
  <nameDetails name="Name 04" phone="555-867-5309" email="none@nothing.no" />
  <nameDetails name="Name 05" phone="555-867-5309" email="none@nothing.no" />
</names>

JavaScript 示例:

function buildNameDropdown(data, elem) { 
    this.data = data;
    this.name = $(data).find('nameDetails');
    this.elem = elem;

    buildNameDropdown.prototype.init = function()
    {
        //Working as desired
        $(this.elem).append($('<option value=""> ----- Select a Name ----- </option>')); 
        //Not working
        $(this.name).each(function()
        {
            //$(this) = the object, not 'this.name'
            $(this.elem).append($('<option value="' + $(this).attr('name') + '">' + $(this).attr('name') + '</option>'));

        });
        $(this.elem).combobox(); // from jQuery UI combobox extension
    };
};


var myNameDropdown = new buildNameDropdown(data, "#ddFullName");
myNameDropdown.init();

我应该如何引用“this”作为每个函数的选择器?

4

1 回答 1

2

复制对this局部变量的引用。这样,它将在回调函数的闭包中可用。

(旁注:您不应该在构造函数中设置原型,那样您将为您创建的每个实例重新分配它。)

function buildNameDropdown(data, elem) { 
  this.data = data;
  this.name = $(data).find('nameDetails');
  this.elem = elem;
};

buildNameDropdown.prototype.init = function() {
  $(this.elem).append($('<option value=""> ----- Select a Name ----- </option>')); 
  var t = this;      
  $(this.name).each(function() {
    $(t.elem).append($('<option value="' + $(this).attr('name') + '">' + $(this).attr('name') + '</option>'));
  });
  $(this.elem).combobox(); // from jQuery UI combobox extention
};
于 2013-04-25T20:03:52.127 回答