[英]how to call user defined jquery function from ajax loaded page
我有2頁
從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.