jquery load 一个form, 然后调用on( "submit", "#login_form", login_function ), submithandler 不被调用

sengw 发布于 2016/07/24 16:11
阅读 1K+
收藏 0
$(document).ready( function () {

var login_func = function ( event ) {
    console.log("-------- POST login form" );
    $.post(
      "/accounts/login/",
      $(this).serialize(),
      function ( data ) {
        var parent = $("#login_form").parent();
        $("#login_form").html( data );
        parent.append( document.createElement(
        "<button type='button' class='btn btn-link' id='id_logout_button'> logout </button> <h4> My Buddy </h4> <div id='id_buddylist_div'> </div>" ));
        $("#id_logout_button").click( logout_func );
        $("id_buddylist_div").load( "/buddylist/");
      }
      );
};

var logout_func = function ( event ) {
      event.preventDefault();
      $.get( "/accounts/logout/",
        function( data, status ){
          $("#id_logout_button").parent().html( data );
          $("#login_form").submit( login_func );
        }
        );
};

$("#login_div").load("/accounts/login/",
  function ( reponseText, statusTxt, xhr ) {
    if ( statusTxt =="success" ){
      console.log("register login form submit handler");
      console.log( $("#login_form") );
      $("#login_form").on("submit", "#login_form", login_func );
    }
    else{
      console.log("failed load register form");
    }
  } );

$("#content_div").load("/content/");

 
});

===========================

下面是 /accounts/login返回的form:

{% load bootstraptags %}
<form id="login_form" role="form" >
   {% csrf_token %}
  {% for field in form %}
  <div class="form-group" >
    {{ field.label }}
    <br>
    {{ field|addInputCSS:"form-control" }}
  </div>
  {% endfor %}
  <div class="form-group" >
    <input type="submit" class="btn btn-default"  value="Submit"> </button>
  </div>
</form>
==============================
console.log结果:

GET http://127.0.0.1:8000/accounts/login/

200 OK

2ms
jquery.js (line 4)
GET http://127.0.0.1:8000/content/
200 OK

2ms
jquery.js (line 4)
register login form submit handler
127.0.0.1:8000 (line 166)
Object[form#login_form]




0
form#login_form

context
Document 127.0.0.1:8000

jquery
"1.11.1"

length
1

selector
"#login_form"

constructor
function(a, b)

init
function(a, b)

add
function(a, b)

addBack
function(a)

=============================

每次点击 submit按钮, login_function从来没被调用, 实在是不知道为什么 ?




加载中
0
sengw
sengw

如果我把:

      $("#login_form").on("submit", "#login_form", login_func );

改作:

$("#login_div").on( "submit", "#login_form", login_func);

可以工作了 . 参数里的selector出来的必须是当前元素的子元素

返回顶部
顶部