根據業務狀況,要把核心的東西變成一個模塊便於複用,慢慢沉澱後,可以更快更高效地編程。javascript
業務核心算法:css
/* 數字檢測 @return 返回2,能被3和7整除 返回1,可以被3整除 返回0,不能被3整除 @author Dev Written in 2019.9 */ function checkNum(number){ if(number % 21 == 0) return 2; else if(number % 3 == 0) return 1; return 0 }
業務邏輯代碼:html
/* @return 返回符合條件的拼接結果,每十個一行; illegal: "unexpected number"; begin > end: "the begin is greater than the end" */ function filterNum(begin, end){ var rst = ''; var cnt = 0; //合法性判斷: if(isNaN(begin) || isNaN(end)) return "unexpected number"; if(begin>end) "the begin is greater than the end"; for(var i = begin ; i <= end; i++){ if(checkNum(i) == 0) continue; rst += ("<span class='"); // 被3除 if(checkNum(i) == 1) rst += ("three "); // 被二者除 else rst += ("twt-one "); rst += ("'>"+ i +"</span>"); cnt ++; if(cnt % 10 == 0 ) rst += '<br/>'; } return rst; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="divide.css"> </head> <body> <label>請輸入開始數字</label> <input type="text" name="" id="begin"> <label>請輸入結束數字</label> <input type="text" name="" id="end"> <button id="smt">提交</button> <hr> <div id="result"> </div> </body> <script type="text/javascript" src="base.js"></script> <script type="text/javascript" src="divide.js"></script> </html>
/* normal style */ span{ display: inline-block; width: 100px; text-align: center; } /* Able to be divisible by three. */ .three{ color: blue; font-weight: bold; } /* Able to be divisible by 3 and 7 */ .twt-one{ color: yellow; background-color: red; }
function $(id){ return document.getElementById(id); } function print(log){ console.log(log); }
/* 數字檢測 @return 返回2,能被3和7整除 返回1,可以被3整除 返回0,不能被3整除 @author Dev Written in 2019.9 */ function checkNum(number){ if(number % 21 == 0) return 2; else if(number % 3 == 0) return 1; return 0 } /* @return 返回符合條件的拼接結果,每十個一行; number wrapper: span illegal: "unexpected number"; begin > end: "the begin is greater than the end" */ function filterNum(begin, end){ var rst = ''; var cnt = 0; //合法性判斷: if(isNaN(begin) || isNaN(end)) return "unexpected number"; // 轉成數值 begin = Number(begin), end = Number(end); if(begin > end) return "the begin is greater than the end"; for(var i = begin ; i <= end; i++){ var num = checkNum(i); if(num == 0) continue; rst += ("<span class='"); // 被3除 if(num == 1) rst += ("three "); // 被二者除 else rst += ("twt-one "); rst += ("'>" + i + "</span>"); cnt ++; if(cnt % 10 == 0 ) rst += '<br/>'; } return rst; } /* 用戶提交數據時觸發 獲取網頁源數據,並在網頁顯示處理結果 */ function onSubmit(){ var begin = $('begin').value; var end = $("end").value; var rst = $('result'); rst.innerHTML = filterNum(begin,end); } // 設置點擊事件函數 $('smt').onclick = onSubmit;