Jquery选择在Backbone中的模板元素中不起作用



我有一个简单的表单作为模板,并有一个初始化方法来根据需要更改文本区域。问题是,我想以文本区域为目标,以便在其上使用Jquery,但Backbone不允许。例如,如果我想执行this.$('textarea').css('height', '1em');,则在控制台中返回以下内容:

[prevObject: jQuery.fn.jQuery.init[1], context: <form>, selector: "textarea"]
context: <form>
length: 0
prevObject: jQuery.fn.jQuery.init[1]
selector: "textarea"
__proto__: Object[0]

如果我尝试this.$el.find('textarea').css('height', '1em'),我会得到类似的结果。

这是我的代码:

模板

<script id="reply-form" type="text/template">
<fieldset>
<textarea rows="3"></textarea>
<input type="button" class="cancel btn btn-small" value="Cancel">
<input type="button" class="send btn btn-success btn-small" value="Send">
</fieldset>   
</script>

views.js

App.Views.Form = Backbone.View.extend({
tagName: 'form',
initialize: function() {
this.startTextarea();
},
startTextarea: function(){
console.log(this.$('textarea').css('height', '1em'));
},
template: _.template( $('#reply-form').html() ),
render: function() {
this.$el.html( this.template() );
return this;
}

会发生什么?

initialize函数中,您不能以这种方式修改HTML,因为模板还没有呈现出来——它找不到任何东西。

我认为这样做的方法是将样式放在模板中,或者放在CSS文件中——这才是它真正的归属。但是,如果在加载视图时需要动态修改模板,则必须在编译模板之前进行修改。有关示例,请参见此处。

startTextarea: function(){
// get the template HTML
var tmpl = $('#reply-form').html();
// modify the template
tmpl = $(tmpl).find('textarea').css('height', '1em')[0].outerHTML;
// compile the template and cache to the view
this.template = _.template(tmpl);
}

最新更新