4
我想使用jQuery的get()方法在我的主頁面中包含一個外部模板,但我遇到了一個問題。mustache.js - 無法使用jQuery獲取外部模板get()方法
顯示在Web瀏覽器的控制檯以下消息:
TypeError: Invalid template! Template should be a "string" but "undefined" was given as the first argument for mustache#render(template, view, partials) - (mustache.min.js:1:9011)
的index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body onload="myTemplate()">
<div id="target">Loading ... </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.2.1/mustache.min.js"></script>
<script type="text/javascript" src="my-script.js"></script>
</body>
</html>
templates.html
<script id="tpl-1" type="text/html">
<p>{{ name }} wins {{ calc }} points</p>
</script>
我-的script.js
// my-script.js
function myTemplate() {
$.get("tpl/templates.html", function(templates) {
var template = $(templates).filter("#tpl-1").html();
var data = {
name: "Guy",
calc: function() {
return 8 + 2;
}
};
var rendered = Mustache.render(template, data);
$('#target').html(rendered);
});
}
儘管如此,它與load()方法效果很好:
// my-script.js
function myTemplate() {
$("#target").load("tpl/templates.html #tpl-1", function() {
var template = $("#tpl-1").html();
var data = {
name: "Guy",
calc: function() {
return 8 + 2;
}
};
var rendered = Mustache.render(template, data);
$('#target').html(rendered);
});
}
你有一個想法,運行get()方法?