繁体   English   中英

车把功能可使用JavaScript格式化货币

[英]Handlebars function to format currency with javascript

我的车把模板中有这个:

<span class="currencyFormatMe">{{_current_price}}</span>

循环返回的示例|: 出价:$ 24000

我想用逗号格式化,但是我失败了。

我有此功能,可以在控制台中使用,但是当通过手柄适应代码库时会失败。

$.fn.digits = function(){ 
    return this.each(function(){ 
        $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
    })
}

我称之为$(“ span.currencyFormatMe”)。digits();

同样,它都可以在控制台中工作,但是在修改后会失败。 任何指针都非常欢迎

使用registerhelper进行了尝试:

Handlebars.registerHelper('formatCurrency',
    $.fn.digits = function(){ 
        return this.each(function(){ 
            $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
        })
    }
);

致电:

{{formatCurrency _current_price}}

您在这里有几个简单的选择。

您可以坚持使用jQuery插件,并在填写了Handlebars模板后应用它; 像这样的东西:

<script id="t" type="text/x-handlebars">
    <span class="currencyFormatMe">{{_current_price}}</span>
</script>

然后:

$.fn.digits = function(){ 
    return this.each(function(){ 
        $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
    })
};

var t = Handlebars.compile($('#t').html());
var h = t({
    _current_price: 1000
});
$('<div>').append(h).find('.currencyFormatMe').digits();

演示: http : //jsfiddle.net/ambiguous/732uN/

或者,您可以将插件转换为Handlebars帮助器,然后在模板中进行格式化。 如果要执行此操作,则只需格式化传递给帮助程序的值,而不用弄乱辅助程序内的$(this) 例如:

<script id="t" type="text/x-handlebars">
    {{formatCurrency _current_price}}
</script>

然后:

Handlebars.registerHelper('formatCurrency', function(value) {
    return value.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
});

var t = Handlebars.compile($('#t').html());
var h = t({
    _current_price: 1000
});

演示: http//jsfiddle.net/ambiguous/5b6vh/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM