[英]Writing my first jQuery plugin
美好的一天,
我正在嘗試編寫我的第一個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();
但它不起作用。 我還缺少什么?
ps我知道有插件可以做到這一點,我只是想學習如何編寫一個然后轉向更大的東西。
TIA,
COSON
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">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.