2016-11-04 32 views
1

美好的一天,寫我的第一個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

+2

當你說這是行不通的,究竟是什麼壞了?你能形容它嗎?你有沒有檢查你的瀏覽器的控制檯是否有錯誤信息? – Terry

+0

我不知道它是否壞了。我檢查了瀏覽器控制檯並沒有看到任何錯誤消息。什麼都沒發生。我希望當我輸入3333時,當我從文本框中刪除時,我應該看到3,333。 – coson

+1

'toLocaleString()'不會將逗號添加到字符串中。 – Barmar

回答

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

+1

請注意,'this'已經是插件函數中的一個jQuery實例。使用'$(this)'是非常低效的。 – plalx

+0

是的,我剛剛在幾分鐘前就明白了這一點。既然你打敗了我,我會給你信貸無論如何。 – coson

+0

我也喜歡你做currentValue.replace的方式。我還記得替換隻是第一次替換而不是倍數。接得好。 – coson