1 <!DOCTYPE html> 2 <html> 3 <head> 4 <META http-equiv=Content-Type content="text/html; charset=utf-8"> 5 <title>if-判斷的基本用法 - by 楊元</title> 6 </head> 7 <body> 8 <h1>if-判斷的基本用法</h1> 9 <!--基礎html框架-->10 <table>11 <thead>12 <tr>13 <th>姓名</th>14 <th>性別</th>15 <th>年齡</th>16 </tr>17 </thead>18 <tbody id="tableList">19 20 </tbody>21 </table>22 23 <!--插件引用-->24 <script type="text/javascript" src="script/jquery.js"></script>25 <script type="text/Javascript" src="script/handlebars-1.0.0.beta.6.js"></script>26 27 <!--Handlebars.js模版-->28 <!--Handlebars.js模版放在script標簽中,保留了html原有層次結構,模版中要寫一些操作語句-->29 <!--id可以用來唯一確定一個模版,type是模版固定的寫法-->30 <script id="table-template" type="text/x-handlebars-template">31 {{#each student}}32 {{#if name}}33 <tr>34 <td>{{name}}</td>35 <td>{{sex}}</td>36 <td>{{age}}</td>37 </tr>38 {{/if}}39 {{/each}}40 </script>41 42 <!--進行數據處理、html構造-->43 <script type="text/javascript">44 $(document).ready(function() {45 //模擬的json對象46 var data = {47 "student": [48 {49 "name": "張三",50 "sex": "0",51 "age": 1852 },53 {54 "sex": "0",55 "age": 2256 },57 {58 "name": "妞妞",59 "sex": "1",60 "age": 1861 }62 ]63 };64 65 //注冊一個Handlebars模版,通過id找到某一個模版,獲取模版的html框架66 //$("#table-template").html()是jquery的語法,不懂的童鞋請惡補。。。67 var myTemplate = Handlebars.compile($("#table-template").html());68 69 //將json對象用剛剛注冊的Handlebars模版封裝,得到最終的html,插入到基礎table中。70 $('#tableList').html(myTemplate(data));71 });72 </script>73 </body>74 </html>
在遍歷student時,由于數據缺失,并不是每一個學生都有name屬性,我們不想顯示沒有name屬性的學生,這時就需要if來做判斷。
{{#if name}}可以用來判斷當前上下文中有沒有name屬性,實際上,它是嘗試去讀取name屬性,如果返回的為undefined、null、""、[]、false任意一個,都會導致最終結果為假。
if還支持多層次讀取,例如:{{#if name.xxx}},這樣寫就假設name屬性是一個map,檢測name屬性中是否包含xxx屬性。
作者:楊元歡迎任何形式的轉載,但請務必注明出處。
新聞熱點
疑難解答