-2

我为一个项目创建了一个 jquery 插件:http: //jsfiddle.net/4kb9R/144/

我希望这个插件既可以用作插件,当然也可以使用一个名为 init 的公共方法,它基本上可以做同样的事情。

我遇到的问题是,当我尝试运行公共初始化函数时,我无法使用以下方法运行私有函数:

   self = this;

   //Start using the amountFormatter
   this.init = function(elements) {
        if(elements instanceof jQuery) {
            //Check the value of each element and update it accordingly
            elements.each(function() {
                var $this = $(this);
                var elementIsInput = $this.is("input");

                value = $this.val() == "" ? $this.text().trim() : $this.val().trim();
                value = (typeof value === 'undefined') ? '0' : value;

                value = thousandSeperator(
                    convertNumber(roundingOfNumber(value, config.rounding))
                );

                //Checks whether we need to add the new amount as text or as a value
                return elementIsInput === true ?
                    elem.val(addCurrencyToNumber(value)) :
                elem.text(addCurrencyToNumber(value));
            });
        }
        else {
            if(elements.length !== 0) {                    
                for (var i = 0; i < elements.length; i++) {
                    var value = elements[i];

                    //I get the error here, when I'm using self;
                    elements[i] = self.addCurrencyToNumber(
                                        self.thousandSeperator(self.convertNumber(self.roundingOfNumber(value, config.rounding)))
                                  );
                }
                return elements;
            }
        }
    };

    this.init(elem);

我这样调用函数:

var containerWithValue = $('.sf-insurance-amount');
var amountToTransform = containerWithValue.text();
var AmountsToFormat = ["4512.45", "784,687", "875943,5975"];

//Shows the original value...
$(".sf-insurance-amount-original").text("Original: " + amountToTransform);

// With options...
containerWithValue.amountFormatter({
    culture: "en",                   
    valuta:  "euro",
    rounding: 3
});

var amountFormatterData = containerWithValue.data('amountFormatter');
var newAmounts = amountFormatterData.init(AmountsToFormat);
console.log(newAmounts);

$.each(newAmounts, function(index, value) {
  $(".sf-insurance-amount-provided ul li").eq(value-1).html(value);
});

任何人都知道这是为什么?我在这里错误地使用了 this 关键字吗?我很想为此找到解决方案。

4

1 回答 1

0

愚蠢的错误。我换了东西。我试过了,就像我想在私有函数中使用公共函数一样。我应该注意到了。如果我想在公共函数中访问私有函数,我只需要在没有this关键字的情况下调用该函数。

所以应该是:

this.init = function(elements) {
    if(elements.length !== 0) {                    
         for (var i = 0; i < elements.length; i++) {
            var value = elements[i];
            elements[i] = addCurrencyToNumber(
                                      thousandSeperator(convertNumber(roundingOfNumber(value, config.rounding)))
                                  );
         }
         return elements;
    }
};
于 2013-08-31T22:11:48.223 回答