如何在Handlebars模板中实现点击对应标题切换文本显示/隐藏
解决Handlebars模板中点击标题切换对应文本显示/隐藏的问题
Hey there! 刚看了你的代码,你遇到的问题根源是重复使用了唯一ID:HTML规范里ID必须是页面唯一的,你给所有标题都用#button、所有文本都用#ff,导致jQuery的$("#button")只会选中第一个匹配的元素,自然只能操作数组的第0项。
下面给你两种修改方案,都能解决问题,其中第一种更简洁推荐:
方案一:用相对选择器(推荐)
这种方法不需要依赖@index,通过DOM结构的相对关系就能定位到对应文本,代码更灵活。
1. 修改Handlebars模板
把重复的ID换成类名,保证每个元素的标识不冲突:
<script id="maino" type="text/x-handlebars-template"> <div class="row"> {{#each names}} <div class="col-xs-12 col-md-3"> <div data-id="{{@index}}"> <!-- 把id换成类title-button --> <h4 class="title-button">{{name}}</h4> <!-- 把id换成类content-text --> <p class="content-text">{{text}}</p> </div> </div> {{/each}} </div> </script>
2. 修改JS代码
用事件委托绑定点击事件,然后通过当前点击元素的兄弟关系找到对应文本:
// 用事件委托绑定到document,确保动态渲染的元素也能触发事件 $(document).on('click', '.title-button', function() { // this指向当前点击的标题,找到它的兄弟元素.content-text并切换显示 $(this).siblings('.content-text').toggle(); });
方案二:绑定并使用@index属性
如果你一定要用到@index,可以把它绑定到元素的data属性上,再通过索引定位元素:
1. 修改Handlebars模板
给标题元素加上data-index属性,绑定@index值:
<script id="maino" type="text/x-handlebars-template"> <div class="row"> {{#each names}} <div class="col-xs-12 col-md-3"> <div data-id="{{@index}}"> <!-- 绑定@index到data-index属性 --> <h4 class="title-button" data-index="{{@index}}">{{name}}</h4> <p class="content-text">{{text}}</p> </div> </div> {{/each}} </div> </script>
2. 修改JS代码
点击时获取data-index的值,再通过索引选中对应文本:
$(document).on('click', '.title-button', function() { // 获取绑定的@index值 const itemIndex = $(this).data('index'); // 选中对应索引的.content-text元素并切换显示 $('.content-text').eq(itemIndex).toggle(); });
另外补充一下:用$(document).on()做事件委托比直接$('.title-button').click()更可靠,因为Handlebars是动态渲染内容的,事件委托能确保后续渲染出来的元素也能触发点击事件。
你的数组定义可以保持不变:
var banners = { names: [ { name: "Lorem ipsum", text: "dolor sit amet, consectetur " }, { name: "aboris nisi", text: "Duis aute irure dolor in reprehenderit " }, { name: "culpa officia", text: "ccaecat cupidatat non" } ] }
内容的提问来源于stack exchange,提问作者chaichaika
相关产品推荐
相关产品推荐

