如何在Backbone.js循环中仅显示每个列表的单个元素?
嘿,别担心英文表达的问题呀~我来帮你解决Backbone.js里这个「每个列表只显示单个值」的需求!结合你给出的代码片段,我整理了几种实用的实现方式,你可以根据自己的场景选择:
方法1:修改模板,直接指定要显示的目标字段
如果你的模板引擎是Handlebars(Backbone常用的模板工具之一),可以借助模板助手精准筛选字段。比如你想只显示calculationValue这个字段的值,修改模板如下:
_template: '<div class="list-container"> {{#each rows}} {{#each this}} {{#if (eq name "calculationValue")}} <div class="list-item">{{value}}</div> {{/if}} {{/each}} {{/each}} </div>',
如果用的是Underscore模板,语法会稍有不同:
_template: '<div class="list-container"> <% _.each(rows, function(row) { %> <% _.each(row, function(field) { %> <% if (field.name === "calculationValue") { %> <div class="list-item"><%= field.value %></div> <% } %> <% }); %> <% }); %> </div>',
方法2:渲染前预处理数据,只保留需要的值
要是不想改动模板,你可以在数据准备阶段(比如视图初始化、数据fetch完成后)先把数据处理成只包含单个值的结构,再传给模板渲染:
// 假设你的数据存在this.model中 const filteredRows = this.model.get('rows').map(row => { // 这里可以换成你想要的字段名,比如'entityType' const targetField = row.find(field => field.name === 'calculationValue'); return targetField ? targetField.value : ''; }); // 把处理后的数据传入模板并渲染 this.$('.list-container').html(this.template({ rows: filteredRows }));
对应的模板可以简化成:
_template: '<div class="list-container"> {{#each rows}} <div class="list-item">{{this}}</div> {{/each}} </div>',
方法3:渲染后通过DOM操作隐藏/移除多余元素
如果已经渲染了所有字段,也可以在afterRender钩子中处理DOM,只保留你需要的那一个值:
afterRender: function() { // 遍历每一行,只保留目标字段对应的元素(这里假设每个字段元素有对应类名) this.$('.list-container .row').each(function() { // 隐藏除了calculationValue之外的所有元素 $(this).children().not('.calculationValue').hide(); // 或者直接移除多余元素:$(this).children().slice(1).remove(); }); return this; // Backbone视图的afterRender建议返回this,保证链式调用 }
注:这种方式需要你在渲染字段时给每个元素加上对应类名,比如<div class="{{name}}">{{value}}</div>。
如果你是想整个列表只显示一个值(比如整个rows里的第一个字段值),那更简单,直接取对应数据即可:
// 模板写法 _template: '<div class="list-container">{{rows.[0].[0].value}}</div>',
或者在JS里直接赋值:
const singleValue = this.model.get('rows')[0][0].value; this.$('.list-container').text(singleValue);
如果还有更具体的场景细节(比如字段数据的实际结构、你到底是要每个行只显示一个还是整个列表只显示一个),可以随时补充说明哦~
内容的提问来源于stack exchange,提问作者Gündoğdu Yakıcı
相关产品推荐
相关产品推荐

