2016-06-09 87 views
1

所以我從Handlebars.js開始,我並不真正瞭解這些內容。請耐心等待我。無法顯示內容的把手

我有三個文件,test.html,test.js和data.js.我希望test.html通過test.js中的Handlebars顯示data.js中的數據。但是,沒有內容可以被看到。我認爲解決方案可能在於某個地方調用某個函數,但我不知道該函數在哪,也不知道在哪裏。

下面是代碼:

的test.html

<head> 
 

 
    <script src="js/jquery.js"> 
 
    </script> 
 
    <script src="js/handlebars-v3.0.3.js"> 
 
    </script> 
 
    <script src="test.js"> 
 
    </script> 
 
    <script src="data.js"> 
 
    </script> 
 
    <script src="js/bootstrap.js"> 
 
    </script> 
 

 
    <link href="css/bootstrap.css" rel="stylesheet"> 
 
    <link href="css/gallery.css" rel="stylesheet"> 
 

 
</head> 
 

 
<body> 
 

 
    <script id="image-templatexxx" type="text/x-handlebars-template"> 
 
    {{name}}</br> 
 
    {{author}}</br> 
 
    <img style="height:600" src="{{src}}" /> 
 
    </script> 
 

 
    <div id="test-content"> 
 
    </div> 
 

 
</body>

data.js

var testdata = { 
 
    src: "https://upload.wikimedia.org/wikipedia/commons/thumb/9/97/The_Earth_seen_from_Apollo_17.jpg/600px-The_Earth_seen_from_Apollo_17.jpg ", 
 
    name: "The Earth seen from Apollo 17", 
 
    author: "Ed g2s" 
 
};

test.js

var source = $("#image-templatexxx").html(); 
 
var testtemplate = Handlebars.compile(source); 
 
var testhtml = testtemplate(testdata); 
 
$('#test-content').html(testhtml); \t

非常感謝這一點。

+1

在test.js之前包含data.js,並且還考慮將代碼包裝在文檔中。 –

+0

@HectorBarbossa你會介意準備一個完整的答案嗎? – Jerzyk

+0

@Jerzyk Just did :) –

回答

1

請在test.js之前包含data.js。否則,在使用句柄生成html字符串時,未定義testdata。以下代碼

$(document).ready(function() { 
     var testdata = { 
      src: "https://upload.wikimedia.org/wikipedia/commons/thumb/9/97/The_Earth_seen_from_Apollo_17.jpg/600px-The_Earth_seen_from_Apollo_17.jpg ", 
      name: "The Earth seen from Apollo 17", 
      author: "Ed g2s" 
     }; 

     var source = $("#image-templatexxx").html(); 
     var testtemplate = Handlebars.compile(source); 
     var testhtml = testtemplate(testdata); 
     $('#test-content').html(testhtml); 

    }); 

適用於我。