繁体   English   中英

如何从ajax加载页面调用用户定义的jquery函数

[英]how to call user defined jquery function from ajax loaded page

我有2页

  • index.php
  • login.php

从index.php进行ajax调用并获取login.php

index.php:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>Home Page</title>
    <script src="./js/jquery.js"></script>
        <script>
        $(document).ready(function(e) {
            $("a").click(function(e) {
                var model= $.ajax({
                    url: $(this).attr('href'),
                    cache:false,
                    type: "GET",
                    dataType:"json"
                });
                model.done(function(data){
                    $("#body").html(data.bodyy);
                    e.preventDefault();
                });
            });     
                $("form").submit(function(e) {
                            alert("Triggered");
                });
        });

    </script>



    <body>
    <div id="body"><a href="login.php">Login</a>
    </div>
</body>
</html>

这是ajax页面:login.php

<?php
    $body='<form class="form-signin" action="#" method="post" id="login">
        <h2 class="form-signin-heading">Please sign in</h2>
        <input type="text" class="input-block-level" placeholder="username" name="username">
        <input type="password" id="password" class="input-block-level" placeholder="Password" name="password">
        <label class="checkbox">
          <input type="checkbox" value="remember-me"> Remember me
        </label>
        <table><th>
        <button class="btn btn-large btn-primary" type="submit">Sign in</button> </th><th width="5%">
        <h3>  or  </h3></th><th>
         <a class="btn btn-large btn-primary" href="./registration.php" >Register</a></th></table>
      </form>
      <script>
        </script>
';
    $data= array(
        'bodyy' => $body,
        );
        echo json_encode($data);
?>

当我提交登录表单$("form").submit(function(e)没有调用。当我从ajax加载页面调用此$("form").submit(function(e)时,出现此问题

这是因为您在执行jQuery时绑定到表单。 对于“延迟”事件绑定(意味着您想绑定到所有表单,而不仅仅是绑定时的页面上的表单),必须绑定到父元素,然后指定子选择器来触发处理程序, 如:

$("body").on("click", "form", function(e) {});

这将绑定单击主体,但仅在单击作为主体子项的表单时才触发处理程序(如果主体中有不应该执行此操作的表单,则使用更具体的父元素会很有用)。

在jQuery中绑定事件时,请确保在执行绑定时仅绑定到页面上存在的元素,否则它将中断事件绑定。 旁注,如果您需要“移动”元素而不破坏绑定事件,则应使用jQuery的detach函数而不是remove detach函数从页面上删除该元素,但保留事件绑定信息,使您可以将其放置在其他位置,而无需更新事件函数(或处理引用的处置)。

暂无
暂无

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

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