我有一个backbone.js视图,它从HTML中读取一个模板并将其模型中的值插入到模板中。其中一个值在变量title中,它可以足够长来中断页面上的元素流。我想使用Javascript来限制最大值。title可以拥有的字符数,而不是在后端执行,因为最终必须显示完整的title。
在模板呈现后,我尝试选择包含title的div,但似乎无法选择它。否则我怎么做呢?
模板
<script type="text/template" id="tpl_PhotoListItemView">
<div class="photo_stats_title"><%= title %></div>
</script>视图
PhotoListItemView = Backbone.View.extend({
tagNAme: 'div',
className: 'photo_box',
template: _.template( $('#tpl_PhotoListItemView').html() ),
render: function() {
$(this.el).html( this.template( this.model.toJSON() ) );
console.log($(this.el).children('.photo_stats_title')); <!-- returns nothing -->
this.limitChars();
return this;
},
limitChars: function() {
var shortTitle = $(this.el).children('.photo_stats_title').html().substring(0, 10);
$(this.el .photo_stats_title).html(shortTitle);
}
});发布于 2012-07-16 13:18:33
与其尝试在呈现后修改标题,不如在呈现后修改它。
还向模板传递一个maxlength变量,然后:
<script type="text/template" id="tpl_PhotoListItemView">
<div class="photo_stats_title"><%= title.substr(0,maxLength) %></div>
</script>如果title.length小于最大长度,则会显示整个字符串。如果它更大,则只显示第一个maxlength字符。
或者,只需将title的最大长度硬编码到.substr()调用中即可。
如果您需要执行更高级的截断(例如添加“.”)(要截断标题),最好在呈现模板之前修改标题,将标题的截断版本传递给模板
另一种选择是重写Model.parse(response),在模型上创建一个shortTitle属性;这样,无论何时使用模型,它都是可用的
发布于 2012-07-16 13:41:42
有两件事,第一件,为了得到任何View的孩子,我建议你这样做,而不是你正在做的事情:
console.log( this.$('.photo_stats_title') );"this.$“是一个具有特定视图范围的jQuery选择器。
第二件事是包装您的模型来处理这个问题,我不建议在您的模板或视图中验证这一点。在您的模型中,为shortTitle定义一个新属性:
var titleMaxLength = 20;
var YourModel : Backbone.Model.extend({
defaults : {
id : null,
shortTitle : null,
title : null
},
initialize : function(){
_.bindAll(this);
this.on('change:name', this.changeHandler);
this.changeHandler();
},
changeHandler : function(){
var shortTitle = null;
if( this.title ){
shortTitle = this.title.substr(0, titleMaxLength);
}
this.set({ shortTitle : shortTitle }, {silent: true});
}
});https://stackoverflow.com/questions/11505083
复制相似问题