我有一个简单的表单作为模板和一个根据需要更改文本区域的初始化方法。问题是我想定位文本区域以便在其上使用 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>
View .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 文件中——这才是它真正所属的地方。但是,如果您需要在加载 View 时动态修改模板,则必须在编译模板之前进行修改。参见 here举个例子。
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);
}
关于javascript - Jquery 选择在 Backbone 中的模板元素中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13639077/