繁体   English   中英

如何从Backbone.js中的View对象中获取当前模板中的所有元素

[英]How to get all the element from the current template in View object in Backbone.js

如何从backbone.js中的View对象中的当前模板获取所有输入元素,以便我可以检查input元素中的值。

/*template*/

<script id="emptemplate" type="text/template">
<input id="name" value="{name}"/>
<input id="address" value="{address}"/>
<input id="sex" value="{sed}"/>
<footer>
   <button id="save">save</button>
</footer>
</script>

/*javascript*/

var EmployeeView = Backbone.View.extend({
  ...
  render:function(){
  ....
  },
  events:{
    "click #save": "saveData"
  },
  saveData: function (e) {
        var Data = [];
        $('input').each(function (value, key) {
            /*my problem here:
             cannot able to get the value of input element!
             */
            var v = value;
            var k = key;
        });
    }
  });

将渲染功能更新为

render: function(){
       var template = _.template( $("#emptemplate").html(), {} );
       this.$el.html( template );
}

然后尝试...它会将模板添加到您的视图中,然后您可以绑定并对其执行操作

我想出了解决方案,迭代到当前视图中的所有输入元素以从中获取值。 在“saveData”事件处理程序中,当用户单击“保存”按钮时,如下所示:

saveData:function(){
var data=[];
this.$el.find('input').each(function(){
$input=$(this);
//build the array of [key, value]
data[$input.attr('id')] = $input.val();
}
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM