简体   繁体   English

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

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

How to get all the input element from the current template in View object in backbone.js, so that I can check the value in input element. 如何从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;
        });
    }
  });

update your render function to 将渲染功能更新为

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

then try... it will add template to el of your view then you can bind and take actions on it 然后尝试...它会将模板添加到您的视图中,然后您可以绑定并对其执行操作

I come up with the solution, to iterate to all the input element in the current view to get the value from it. 我想出了解决方案,迭代到当前视图中的所有输入元素以从中获取值。 In the "saveData" event-handler when the user click the save button, like this: 在“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