这是我现在拥有的:
$("#number").val(parseFloat($("#number").val()).toFixed(2));
对我来说看起来很乱。我认为我没有正确地链接功能。我必须为每个文本框调用它,还是可以创建一个单独的函数?
如果您要在多个领域进行此操作,或者经常这样做,那么答案可能就是插件。这是jQuery插件的开头,该插件将字段的值格式化为两位小数。它由字段的onchange事件触发。您可能想要其他东西。
<script type="text/javascript">
// mini jQuery plugin that formats to two decimal places
(function($) {
$.fn.currencyFormat = function() {
this.each( function( i ) {
$(this).change( function( e ){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
});
});
return this; //for chaining
}
})( jQuery );
// apply the currencyFormat behaviour to elements with 'currency' as their class
$( function() {
$('.currency').currencyFormat();
});
</script>
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">
也许是这样,如果需要,您可以在其中选择多个元素?
$("#number").each(function(){
$(this).val(parseFloat($(this).val()).toFixed(2));
});
我们修改了Meouw函数以用于keyup,因为当您使用输入时,它可能会更有帮助。
检查此:
嘿,@ heridev,我在jQuery中创建了一个小函数。
您可以尝试下一个:
HTML
<input type="text" name="one" class="two-digits"><br>
<input type="text" name="two" class="two-digits">
jQuery
// apply the two-digits behaviour to elements with 'two-digits' as their class
$( function() {
$('.two-digits').keyup(function(){
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length > 2){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
}
}
return this; //for chaining
});
});
在线演示:
((@ heridev,@vicmaster)