美好的一天,
我正在尝试编写我的第一个 jQuery 插件。我相信这很简单。当我将注意力集中在文本框上时,我想删除任何货币格式(即删除“$”、“,”和“.”)。当我将焦点移出文本框时,我想应用数字逗号格式。
(function($) {
$.fn.enableCommify = function() {
$(this).on('focus', function () {
var currentValue = $(this).val().trim();
var stripped = currentValue.replace(',', '');
$(this).val(stripped);
});
$(this).on('focusout', function () {
var currentValue = $(this).val();
$(this).val(currentValue.toLocaleString());
});
}
}(jQuery));
当我使用它时:
$('.commify').enableCommify();
但它不起作用。我还缺少什么?
附:我知道有一些插件可以做到这一点,我只是想学习如何编写一个插件,然后继续做更大的事情。
TIA,
科森
最佳答案
toLocaleString()
仅在应用于数字时添加逗号。但 $(this).val()
是一个字符串,而不是数字。使用 parseInt()
将其转换为数字。
此外,要替换字符串的多个匹配项,您需要使用带有 g
修饰符的正则表达式。
(function($) {
$.fn.enableCommify = function() {
$(this).on('focus', function() {
var currentValue = $(this).val().trim();
var stripped = currentValue.replace(/,/g, '');
$(this).val(stripped);
});
$(this).on('focusout', function() {
var currentValue = parseInt($(this).val(), 10);
$(this).val(currentValue.toLocaleString());
});
}
}(jQuery));
$('.commify').enableCommify();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="commify">
关于javascript - 编写我的第一个 jQuery 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40433052/