我想用jQuery的get()方法在我的主页中包含一个外部模板,但是有一个问题。
Web浏览器的控制台中显示以下消息:
TypeError:无效的模板!模板应为“字符串”,但必须为胡须#render(模板,视图,部分)的第一个参数给出“未定义”-(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>
Run Code Online (Sandbox Code Playgroud)
templates.html
<script id="tpl-1" type="text/html">
<p>{{ name }} wins {{ calc }} points</p>
</script>
Run Code Online (Sandbox Code Playgroud)
my-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);
});
}
Run Code Online (Sandbox Code Playgroud)
不过,它可以与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);
});
}
Run Code Online (Sandbox Code Playgroud)
您有运行get()方法的想法吗?
小智 0
$(document).ready(function(){
function myTemplate() {
$.get("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);
});
}
$('#target').on('load', myTemplate());
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1000 次 |
| 最近记录: |