简体   繁体   English

编写我的第一个jQuery插件

[英]Writing my first jQuery plugin

Good Day, 美好的一天,

I'm trying to write my first jQuery plugin. 我正在尝试编写我的第一个jQuery插件。 I believe it to be a simple one. 我认为这是一个简单的。 When I focus in on a textbox, I want to remove any currency formatting (ie removing '$', ',', and '.') When I focus out of a textbox, I want to apply numeric comma formatting. 当我专注于文本框时,我想删除任何货币格式(即删除'$',','和'。')当我从文本框中聚焦时,我想应用数字逗号格式。

(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));

and when I use it: 当我使用它时:

$('.commify').enableCommify();

but it's not working. 但它不起作用。 What else am I missing? 我还缺少什么?

ps I'm aware that there are plugins that do this, I'm just trying to learn how to write one then move on to bigger things. ps我知道有插件可以做到这一点,我只是想学习如何编写一个然后转向更大的东西。

TIA, TIA,

coson COSON

toLocaleString() only adds commas when it's applied to a number. toLocaleString()仅在将数字应用于数字时添加逗号。 But $(this).val() is a string, not a number. 但是$(this).val()是一个字符串,而不是一个数字。 Use parseInt() to convert it to a number. 使用parseInt()将其转换为数字。

Also, to replace multiple matches of a string, you need to use a regexp with the g modifier. 此外,要替换字符串的多个匹配项,您需要使用带有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"> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM