我想用用jQuery mustache.js在我的HTML5應用程序,但我不能讓所有的組件協同工作。每個文件都找到了,這裏沒有問題(模板加載了roght,我可以在Firebug調試器中看到它的值)。Mustache.js + jQuery:最簡單的工作示例是什麼?
這裏是我的index.html:
<!DOCTYPE html>
<html lang="fr">
<head><meta charset="utf-8"></head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="../js/jquery.mustache.js"></script>
<script src="../js/app.js"></script>
<div id="content"></div>
</body>
</html>
這裏是我的app.js文件:
$(document).ready(function() {
var template = $.get('../templates/article.mustache');
$.getJSON('../js/article.json', function(view) {
var html = Mustache.to_html(template, view);
$("#content").append(html);
});
});
的jquery.mustache.js文件是一個從https://github.com/janl/mustache.js產生:
/*
Shameless port of a shameless port
@defunkt => @janl => @aq
See http://github.com/defunkt/mustache for more info.
*/
;(function($) {
// <snip> mustache.js code
$.mustache = function(template, view, partials) {
return Mustache.to_html(template, view, partials);
};
})(jQuery);
注意到顯示。螢火告訴我
鬍子沒有定義
請參閱捕獲:
我知道缺少了什麼,但我不能告訴。
謝謝。
編輯: 正確和完整的回答到最小例子如下:
- 寫劇本模板,不從文件中加載它
- 同上爲JSON數據
- 讀jQuery的是如何產生和使用
$.mustache.to_html
函數代替(在案githu B)Mustache.to_html
(感謝@mikez302) - 重構「直到你放棄
$(document).ready(function() { var template = " ... {{title}} ... "; var json = {title: "titre article" } var article = $.mustache(template, json); $("#content").append(article); });
但是,它很容易從另一個文件中讀取JSON:
$(document).ready(function() { var template = " ... {{title}} ... "; $.getJSON('../js/article.json', function(view) { var article = $.mustache(template, view); $("#content").append(article); }); });
你終於可以還閱讀來自文件的模板:
$(document).ready(function() { $.getJSON('../js/article.json', function(view) { $.get("../templates/article.mustache", function(template) { var article = $.mustache(template, view); $("#content").append(article); }); }); });
工作示例(無l oading順序問題):
$(document).ready(function() { $.getJSON('../js/article.json', function(model) { return onJSON(model); }); }); function onJSON(model) { $.get("../templates/article.mustache", function(view) { var article = $.mustache(view, model); $("#content").append(article); }); }
我會把所有的JavaScript **放在**內容後面。 [LINK](http://developer.yahoo.com/blogs/ydn/posts/2007/07/high_performanc_5/) – Sparky
感謝您的提示。我現在不在尋找優化,我螞蟻讓我的代碼工作 –
我發佈它作爲評論,而不是答案。當然,您在其中加載腳本的**命令**也包括_also_,以使代碼正常工作。如果你是JavaScript的初學者,這個信息是一個關鍵的'必讀'。所有初學者都知道他們需要加載jQuery _before_他們加載jQueryUI或任何其他jQuery插件? – Sparky