我有模糊事件的功能,并使用正则表达式来替换模糊事件的输入值。但我有一些问题,当输入字段读取下一个事件模糊时,模糊事件仍然运行它,它使我的正则表达式运行两次并生成一个NaN,我真的很感谢你的帮助。这是我的代码:
$(document).ready(function(){
$('#myNumber').on('blur', function ({target}) {
if ($(this).val()) {
let number = parseInt($(this).val());
const num = '$ ' + number.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
$(this).val(num);
}
});
})

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input type="text" id="myNumber">
</body>
</html>
&#13;
答案 0 :(得分:1)
这是因为在第一次$
事件执行后你有blur
个签名。
从js
功能中删除它。
$(document).ready(function(){
$('#myNumber').on('blur', function ({target}) {
if ($(this).val()) {
let number = parseInt($(this).val());
const num = number.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
$(this).val(num);
}
});
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<span>$</span><input type="text" id="myNumber">
</body>
</html>
答案 1 :(得分:1)
$('#myNumber').on('blur', function ({target}) {
if ($(this).val()) {
var numberValue = $(this).val().trim();
if(numberValue.charAt(0) == '$')
{
var numberValue1 = $(this).val().trim().slice(2);
let number = parseInt(numberValue1);
const num = '$ ' + number.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
$(this).val(num);
}
else
{
let number = parseInt($(this).val());
const num = '$ ' + number.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
$(this).val(num);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myNumber">
答案 2 :(得分:0)
问题在于,当您第二次获得该值时,val()
中的值为'$',因此它不是数字,而是导致NaN
问题。每次进入函数时都应该替换符号。
我也将const num =
更改为var num = ...
,因为我不确定使用会改变的const是否合适......
$(document).ready(function(){
$('#myNumber').on('blur', function ({target}) {
if ($(this).val()) {
let number = parseInt($(this).val().replace('$',''));
var num = number.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
num = '$ ' + num;
$(this).val(num);
}
});
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input type="text" id="myNumber">
</body>
</html>
答案 3 :(得分:0)
检查此fiddle ..
添加此js ..
$(document).ready(function(){
$('#myNumber').on('blur', function ({target}) {
if ($(this).val()) {
let number = parseInt($(this).val());
const num = number.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
$(this).val(num);
}
});
});
&#13;