IE选择不附加选项

时间:2012-02-22 22:23:41

标签: javascript jquery

我创建了一个货币转换器对象,除了在IE中它工作得很好。没有选项附加到select元素。我一直试图找到一个解决方案几个小时,但无法弄清楚发生了什么。我是javascript的新手,所以我可能会做一些完全错误的事情而不确定是什么。似乎没有从fetch中调用render方法。感谢

var CurrencyConverter = {

  // Initialize Currency Converter
  // total: jQuery wrapped object that contains the price to convert
  // select: jQuery wrapped select element to render the options tag in
  init: function  (total, select) {

    var that = this;

    this.total = total;
    this.base_price = accounting.unformat(this.total.text());
    this.select = select;

    this.fetch();

    select.change(function () {
      var converted = '',
          formated = '';

      fx.settings = { from: fx.base, to: this.value };
      converted = fx.convert(that.base_price);
      formated = accounting.formatMoney(converted, { symbol: this.value,  format: "%s %v", precision: "0" });

      $(that.total).text(formated);
    });
  },


  // Render Currency Options
  render: function () {

    var that = this,
        accumulator = [],
        frag = '';

    for (var propertyName in fx.rates) {
      accumulator.push(propertyName);
    }

    $.each(accumulator, function ( i, val ) {
      var the_price = $(document.createElement('option')).text(val);

      if (val == fx.base) {
        the_price.attr('selected', 'true');
      }

      // TODO: not optimal to run append through each iteration
      that.select.append(the_price);
    });

  },

  // Fetch & set conversion rates
  fetch: function () {

    var that = this;

    // Load exchange rates data via the cross-domain/AJAX proxy:
    $.getJSON(
        'http://openexchangerates.org/latest.json',
        function(data) {
          fx.rates = data.rates;
          fx.base = data.base;

          that.render();
        }
    );
  }
};

if ($('#currency-select')) {
  CurrencyConverter.init($('#price'), $('#currency-select'));
}

2 个答案:

答案 0 :(得分:1)

是的,我也是这样做的。不知道它是否是解决这个问题的正确方法,但它有效,这意味着.select是一个jQuery结果:

  

that.select.get(0)。新增(the_price.get(0))

Tutorial about working

答案 1 :(得分:1)

你的问题是范围。

init: function (total, select) {

    var that = this; // Ok, `that` is `init`...

    this.total = total;
    this.base_price = accounting.unformat(this.total.text());
    this.select = select; // So `init.select = select`...
    .
    .
    .

render : function () {
    var that = this, // Ok, `that` is `render`
    accumulator = [],
    frag = '';
    .
    .
    .
    that.select.append(the_price); // ?????

解决此问题的最简单方法是创建构造函数而不是文字对象,这样您就可以将$select作为任何方法中有权访问的对象传递。

var CurrencyConverter = function($select){
    this.init = function(){ ... }
    this.render = function() { $select.append('...'); }
    .
    .
    .
};
var currency = new CurrencyConverter($('select'));