编写我的第一个jQuery插件

时间:2016-11-04 23:23:12

标签: javascript jquery

美好的一天,

我正在尝试编写我的第一个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();

但它没有用。我还缺少什么?

P.S。我知道有插件可以做到这一点,我只是想学习如何写一个然后转向更大的东西。

TIA,

COSON

1 个答案:

答案 0 :(得分:0)

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">

相关问题