返回目錄javascript
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": 18 52 }, 53 { 54 "sex": "0", 55 "age": 22 56 }, 57 { 58 "name": "妞妞", 59 "sex": "1", 60 "age": 18 61 } 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來作判斷。html
{{#if name}}能夠用來判斷當前上下文中有沒有name屬性,實際上,它是嘗試去讀取name屬性,若是返回的爲undefined、null、""、[]、false任意一個,都會致使最終結果爲假。java
if還支持多層次讀取,例如:{{#if name.xxx}},這樣寫就假設name屬性是一個map,檢測name屬性中是否包含xxx屬性。jquery