【问题标题】:Jquery selection is not working in template elements in BackboneJquery 选择在 Backbone 的模板元素中不起作用
【发布时间】:2012-11-30 04:36:41
【问题描述】:

我有一个简单的表单作为模板和一个初始化方法来根据需要更改文本区域。问题是我想定位 textarea 以便在其上使用 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;
}

会发生什么?

【问题讨论】:

    标签: javascript jquery templates backbone.js


    【解决方案1】:

    您不能在 initialize 函数中以这种方式真正修改 HTML,因为模板尚未呈现 - 它不会找到任何东西。

    我认为做到这一点的方法是将样式内容放在模板中,或者放在 CSS 文件中——这确实是它所属的地方。但是,如果您需要在加载视图时动态修改模板,则必须在编译模板之前进行。示例见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);
    }
    

    【讨论】:

    • 我就是这么想的。但是,我能做些什么来操作通过模板创建的对象呢?即使我添加 this.render() 进行初始化,我也会得到相同的结果。
    • @RobertSmith 如果不能直接放在模板中,为什么不放在render 函数中呢?如果非要直接修改模板,请看我上面的更新。
    • 非常感谢...但令人惊讶的是它不应用 css。这很奇怪。
    • @RobertSmith 我实际上并没有更新模板——请参阅我的更新。
    • 太棒了!我认为我想知道的几乎所有事情都可以使用事件来完成,所以我很高兴露营:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多