javascript 使用主干中的输入捕获表单提交事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18425684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:53:17  来源:igfitidea点击:

Capturing form submit events using enter in backbone

javascriptbackbone.js

提问by avis

My backbone.js form has a single textfield (no submit button). I need to capture submit event (using enter key) in the view. Below is the sample code. Somehow the submit method is not called on pressing enter. Instead the form goes for a reload.

我的backbone.js 表单只有一个文本字段(没有提交按钮)。我需要在视图中捕获提交事件(使用回车键)。下面是示例代码。不知何故,按下回车键时不会调用提交方法。相反,表格会重新加载。

Script :

脚本 :

var FormView = Backbone.View.extend({
    el: '#form',

    events: {
        "submit": "submit",
    },

    initialize: function () {
        console.log("initialize");
    },

    submit: function (e) {
        e.preventDefault();
        console.log("submit");
    }
});

new FormView();

HTML :

HTML :

<form id="form">
  <input type="text"/>        
</form>

回答by kumarharsh

Add this to your Backbone view:

将此添加到您的 Backbone 视图中:

events: {
  'submit form': 'submit'
}

Also, note that in your HTML, the form action has to be defined.

另请注意,在您的 HTML 中,必须定义表单操作。

If you don't have the action defined, then do this:

如果您没有定义操作,请执行以下操作:

events: {
  'keyup': 'processKey'
}

processKey: function(e) { 
  if(e.which === 13) // enter key
    this.submit();
}

回答by Gamak

If you're having trouble capturing submit events ensure that your 'el' property is defined in your view.

如果您在捕获提交事件时遇到问题,请确保您的 'el' 属性已在您的视图中定义。

var myView = Backbone.View.extend({
    el: $(body), 
    events: {
       "submit form": "doMethod" 
    }, 
    doMethod: function(e) {
        e.preventDefault();  
        console.log('form fired');
    }  
});