【问题标题】:JQuery HTML5 formjQuery HTML5 表单
【发布时间】:2014-05-05 13:58:03
【问题描述】:

我有一个简单的表格:

 <div class="container">
        <div class="row">
            <div class="col-md-4 col-md-offset-4" >
                <form class="form-signin" role="form" id="login-form">
                  <h2 class="form-signin-heading">Please sign in</h2>
                  <input type="email" class="form-control" placeholder="Email address" required autofocus>
                  <input type="password" class="form-control" placeholder="Password" required>
                  <label class="checkbox">
                    <input type="checkbox" value="remember-me"> Remember me
                  </label>
                  <button class="btn btn-lg btn-primary btn-block" type="submit" id="login-but-sub">Sign in</button>
                </form>
          </div> <!-- form container -->
</div>
    </div> <!-- /container -->

在 HTML 5 Web 应用程序中,(如果有差异,则为 ember JS), 如here 所述,HTML 5 表单验证完美运行。 我正在附加一个 JQuery 事件:

$(function(){
    /*Try to restore user once upon loading*/
    restore_user();
    App = Ember.Application.create({ 
                        LOG_TRANSITIONS: true, });

    client = new client()


    App.Router.map(function() {
        this.route('login');
    });

    App.IndexRoute = Ember.Route.extend({
        setupController: function(controller) {
            console.log(client);
            if(!client.isLoggedIn()){
                this.transitionTo('login')
            }
        }
});
    $("#login-but-sub").submit(function(event){
    console.log("login clicked");
});

});

事件似乎从未被触发的问题...... 如果我将其更改为:

    $("body").submit(function(event){

    $("body").on('submit','body',function(event)

那么它也可以工作。 第一个有什么问题?

【问题讨论】:

  • 提交事件在&lt;form&gt;而不是&lt;button&gt;上触发
  • @anderssonola 这是 OP 的问题,您应该将其发布为答案
  • 您尝试过 $("form").submit(function(event){ 而不是正文
  • 应该是$("#login-form").submit()$("#login-form").on('submit')
  • 仅供参考,我认为$("body").on('submit','body',function(event){...}); 不会起作用

标签: javascript jquery html ember.js


【解决方案1】:

提交事件不会在&lt;button&gt; 上触发,而是在&lt;form&gt; 上触发。

在您的示例中,提交事件冒泡到&lt;body&gt;

【讨论】:

    【解决方案2】:

    来自docs

    当用户尝试提交时,提交事件被发送到一个元素 提交表格。它只能附加到元素上。表格可以 通过单击显式提交, , 或 , 或按 Enter 当某些表单元素具有焦点时。

    因此,您应该将.submit() 用于&lt;form&gt; 元素:

    $("#login-form").submit(function(event){
        console.log("login clicked");
    });
    

    好像你的表单是动态添加的,如果是,那么你需要使用event delegation

    $("body").on('submit','#login-form',function(event) {
        console.log("login clicked");
    });
    

    【讨论】:

    • 对不起,这不起作用,尝试使用它并没有触发日志(之前尝试过)。
    【解决方案3】:
    $('.form-signin').submit() will work.
    

    提交事件属于表单,不是提交按钮

    【讨论】:

    • 这里也一样,经过测试并没有触发。 (也测试过将其添加到表单中,但没有。
    • 尝试在console.log("login clicked"); 之后添加return false;,这将阻止表单提交(以及页面重新加载)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 2011-08-06
    • 2012-07-20
    • 1970-01-01
    相关资源
    最近更新 更多