에 jQuery,가장 좋은 방법은 무엇일 포맷 번호를 2 진수까요?
-
20-08-2019 - |
문제
이것은 내가 지금:
$("#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 기 때문에 사용하는 경우에는 입력을 더 도움이 될 수 있습니다.
이를 확인:
Hey there!, @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)
제휴하지 않습니다 StackOverflow