2012-02-22 62 views
1

我創建了一個貨幣轉換對象,除了在IE中它工作得很好。沒有任何選項會附加到select元素。我一直在努力尋找一個解決方案几個小時,但無法弄清楚發生了什麼事情。我是新來的JavaScript,所以我可能會做一些完全錯誤的事情,只是不知道是什麼。看起來,render方法沒有從fetch中調用。謝謝IE選擇不添加選項

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')); 
} 

回答

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')); 
+0

我重寫了整個事情,範圍絕對是問題謝謝你的幫助! – 2012-02-24 16:48:41

1

你好,我也跑了。不知道這是否是解決這個正確的方式,但它的工作原理,這意味着that.select是一個jQuery結果:

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

Tutorial about working