怎麼用javascript做資料的格式化

來源:互聯網
上載者:User
怎麼用javascript 做資料的格式化        我們在項目中都有用過金額數字及日期等資料格式化輸出顯示,比如前面加上“¥”,數值取小數點後兩位,短日期時間等。一般的進階語言及開發工具都有提供相應的轉換函式如format之類,可是我在最近做web網上銀行相關的系統時,卻遇到這個很麻煩的問題,就是javascript不提供這種format函數,查了些資料,知道vbscript是有格式化函數的,可是vbscript是微軟專用的,無奈只好用Regex,可Regex也不能夠很通用地解決各種類型轉換問題,真的是很鬱悶,無意中找到看到一個AJAX開發工具的示範,看到它的資料有顯示“¥”和數值小數點後兩位格式化,馬上下載了看了下,發現它居然是用javascript+XSL實現了通用的格式化函數,下載AJAX WebShop後,我找到它的system.js這個檔案,開啟找到以下函數:
function FormatFloat(value,mask){       return BasicFormat(value,mask,'FormatNumber')}function FormatDate(varDate, bstrFormat, varDestLocale){       return BasicFormat(varDate,bstrFormat,'FormatDate',varDestLocale);}function FormatTime(varTime, bstrFormat, varDestLocale){       return BasicFormat(varTime,bstrFormat,'FormatTime',varDestLocale);}function BasicFormat(value,mask,action,param){       var xmlDoc;       var xslDoc;       var v='<formats><format><value>'+value+'</value><mask>'+mask+'</mask></format></formats>';       xmlDoc=parseXML(v);        var x;        if(isIE)              x='<xsl:stylesheet xmlns:xsl="uri:xsl">'       else              x='<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">';       x+='<xsl:template match="/">';       if(isIE) {              x+='<xsl:eval>'+action+'('+value+',"'+mask+'"';              if(param)x+=','+param;              x+=')</xsl:eval>';       }       else              x+='<xsl:value-of select="format-number('+value+',/''+mask+'/')" />';        x+='</xsl:template></xsl:stylesheet>';       xslDoc=parseXML(x);       var s;       if(isIE)        s= xmlDoc.transformNode(xslDoc)       else{              //for mozilla/netscape         var processor = new XSLTProcessor();               processor.importStylesheet(xslDoc);              var result = processor.transformToFragment(xmlDoc, xmlDoc);        var xmls = new XMLSerializer();         s = xmls.serializeToString(result);       }       return s;}
看來他們對xsl用得可真是出神入化了,居然這樣就可以實現很通用的格式化轉換了,當然不客氣了,直接加到我的函數庫中哈。       這個代碼偶沒有看得很懂,不過確實很管用,請對XSL精通的朋友分析下也好讓我們學習下。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.