gpt4 book ai didi

javascript - 我可以在 app.js 文件中使用 Handlebars 模板吗

转载 作者:行者123 更新时间:2023-12-03 06:22:45 25 4
gpt4 key购买 nike

我正在制作一个作品集页面,我想要一张逐渐消失的图片并显示其背后图像的文本。我实现了对数据的硬编码。

像这样。

index.html

  <div class="col-sm-6">

<h4>Freelance Work</h4>

<img src="/images/andersen.png" class="portfolio_pic" id="test_pic">

<div id="test_text">
<p>Site for a structural engineer.</p>
<p><strong>Languages:</strong> JavaScript, HTML, CSS</p>
<p><strong>Other:</strong> Git, Bootstrap, GoDaddy Hosting</p>
</div>

<p><a href="https://andersen-engineering.com/">Andersen Engineering</a></p>
<p><a href="https://github.com/nwimmer123/david-excel">GitHub Link</a></p>

</div>

样式.css

#test_text {
margin-top: -220px;
min-height: 210px

}

#test_pic {
max-height: 250px;
border: medium groove #660033;
}

app.js

  $('.test_text').hide();

$('.test_pic').hover(function () {
$(this).stop().animate({
opacity: .1
}, 200);
$('.test_text').show();
}, function () {
$(this).stop().animate({
opacity: 1
}, 500);
$('.test_text').hide();
});

问题是当我使用此代码从我的 Mongoose 数据库中引入相同的信息时

index.html

<div class="col-sm-6"> 
<div class="list-group" id="portfolio_items-list">
<script id="portfolio_items-template" type="text/x-handlebars-template">
{{#each portfolio_items}}
<h4>{{title}}</h4>

<img src={{image}} class="portfolio_pic" id="test_pic">

<div id="test_text">
<p>{{description}}</p>
<p><strong>Languages: </strong>{{language}}</p>
<p><strong>Frameworks: </strong>{{framework}}</p>
<p><strong>Libraries: </strong>{{library}}</p>
<p><strong>Database: </strong>{{database}}</p>
<p><strong>Other: </strong> {{other}}</p>
</div>

<p><a href={{sitelink}}>{{sitename}}</a></p>

<p><a href={{githublink}}>GitHub Link</a></p>

{{/each}}
</script>
</div>
</div>

app.js

  var source = $('#portfolio_items-template').html();
var template = Handlebars.compile(source);

//get all database items

$.get(baseUrl, function (data) {
var dataHtml = template({ portfolio_items: data});
$("#portfolio_items-list").append(dataHtml);
});

然后 test_pic 和 test_text id 没有唯一的 ID,因此 javascript 隐藏/显示/不透明度技巧不起作用。我在想,如果我可以将模板引入 app.js 并将每个Portfolio_items 数据库ID 加载为隐藏/显示/不透明JS 代码的唯一ID,那么它可能会起作用。另一种选择是通过 Handlebars 模板使唯一的 id 出现在 index/html 文件中,然后每次使用该 id 硬编码复制 hide/show/opacity js 代码,但这非常不干燥。

有什么想法吗?

谢谢!

最佳答案

Handlebars 中 {{each}} 循环的索引可通过 {{@index}} 获取,因此您可以执行类似 id="test-pic-{{@ index}} 生成唯一的 id。

FWIW,您还可以仅在 .css 中完成您创建的效果(见下文)。

.container {
width:50%;
height:250px;
overflow: hidden;
background: rgba(0, 0, 0, 0.5);
transition: all .3s ease;
}

.container:hover {
background: rgba(0, 0, 0, 0.1);
}


.text {
font-size: 2em;
opacity: 0;
transition: all .3s ease;
}

.container:hover .text {
opacity:1;

}
<div class="container">
<div class="text">
<p>hello</p>
<p>test</p>
</div>
</div>

关于javascript - 我可以在 app.js 文件中使用 Handlebars 模板吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38794645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com