DIV CSS 佈局教程網

用 jQuery 打造統計字串出現次數的小工具
編輯:JQuery特效代碼     

以下是一個實用的小工具:把 jQuery 原始碼貼進文字框,就能統計各字串出現的次數,也能查詢單一字串出現了幾次。對於想分析程式碼、評估壓縮空間的人來說相當方便。

. 代碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"/>
<title>工具:統計 jQuery 中各字符串出現次數</title>
<script src="https://demo.jb51.net/jslib/jquery/jquery.js" type="text/javascript"></script>
</head>
<body>
<p>源文件(將 jQuery 源碼復制到下面的文本域):</p>
<p><textarea id="myjquery" style="width: 510px; height: 250px; padding: 2px;">..</textarea></p>
<p><input id="mybtn2" style="position: relative; left: 349px;" type="button" value="統計所有字符串出現次數" /></p>
<div id="myshow2" style="width: 500px; height: 250px; border: 1px dotted #8B8D72; overflow: auto; padding: 5px;"></div>
<p><label for="myinput">字符串:<input id="myinput" type="text" /> <input id="mybtn1" style="position: relative; left: 130px;" type="button" value="統計單個字符串出現次數" /> </label></p>
<div id="myshow1" style="width: 500px; height: 100px; border: 1px dotted #8B8D72; overflow: auto; padding: 5px;"></div>
</body>
</html>

核心邏輯是:先以正則表達式為每個關鍵字建立對應的 RegExp 物件,再用 exec 迴圈比對並累加次數,最後依需求排序輸出。點擊「統計所有字符串出現次數」後會發現,像 "string" 這樣的字串竟出現了 44 次;若用一個變數來取代,再經壓縮工具處理,還能進一步縮小檔案。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved