我正在练习使用车把显示数据,但我被卡住了。在我的控制台中,我可以看到它正在从我的 api 中提取信息,但车把中的 HTML 未在页面上呈现。谁能告诉我发生了什么事吗?这是我的代码,它全部构建在本地服务器上:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
<title>Document</title>
</head>
<body>
<div id="meme-container">
<!-- Create a container for the rendered memes -->
<script id="meme-template" type="text/x-handlebars-template">
{{#each memes}}
<div class="memes">
<img src="{{url}}" alt="{{name}}">
<p>{{name}}</p>
</div>
{{/each}}
</script>
</div>
<script>
//script
$(document).ready(function () {
$.get("https://api.imgflip.com/get_memes", function (data) {
const templateSource = $("#meme-template").html();
const template = Handlebars.compile(templateSource);
const renderedHTML = template(data.data.memes); // Assuming the memes are in data.data.memes
// Append the rendered HTML to a container on your webpage
$("#meme-container").html(renderedHTML);
// Handle the response data here
console.log(data); // For testing purposes
});
});
</script>
</body>
</html>
我已经仔细检查过这些名字是不是我想的那样,没有拼写错误。
我已将模板移出
<div>
并稍微修改了代码。
const renderedHTML = template(data.data); // no need to pass since the template is going to look for key called memes in the passed object.
$(document).ready(function() {
$.get("https://api.imgflip.com/get_memes", function(data) {
const templateSource = $("#meme-template").html();
const template = Handlebars.compile(templateSource);
const renderedHTML = template(data.data); // no need to pass since the template is going to look for key called memes in the passed object.
// Append the rendered HTML to a container on your webpage
$("#meme-container").html(renderedHTML);
// Handle the response data here
console.log(renderedHTML); // For testing purposes
});
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
<body>
<div id="meme-container">
</div>
<!-- Create a container for the rendered memes -->
<script id="meme-template" type="text/x-handlebars-template">
{{#each memes}}
<div class="memes">
<img src="{{url}}" alt="{{name}}">
<p>{{name}}</p>
</div>
{{/each}}
</script>
</body>
</html>