我为项目创建了一个jquery插件: http://jsfiddle.net/4kb9R/144/
我希望这个插件既可以用作插件,也可以使用一个名为init的公共方法,它基本上可以做同样的事情。
我遇到的问题是,当我尝试运行公共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);
});
任何人都知道为什么会这样?我在这里错误地使用了这个关键字吗? 我很乐意为此找到解决方案。
答案 0 :(得分: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;
}
};