我有以下HTML / JQuery:
<!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>Login</title>
<script src="jQuery.js"></script>
<script>
$(document).ready(function(){
$(function(){
$("#sb").click(function(e){
e.preventDefault();
getmessage = "Yes";
getmessage = encodeURIComponent(getmessage);//url encodes data
$.ajax({
type: "POST",
url: "get_login.php",
data: {'getmessage': getmessage},
dataType: "json",
success: function(data) {
$("#message_ajax").html("<div class='successMessage'>" + data.message +"</div>");
}
});
});
});
});
</script>
</head>
<body>
<h1>Login</h1>
<p>Please enter your e-mail and password</p>
<form name = "loginform" action = "http://dev.speechlink.co.uk/David/get_login.php" method = "post">
<p>E-mail<input name = "username" type="text" size="25"/><label id ="emailStatus"></label></p>
<p>Password<input name = "password" type="text" size="25"/><label id ="passwordStatus"></label></p>
<p><input type="hidden" name="usertype" value = "SupportStaff" /></p>
<p>><input type ="button" id = "sb"value="Create Account"/></p>
</form>
<div id = "message_ajax"></div>
</body>
</html>
我无法在用户按下“创建帐户”按钮时触发事件处理程序(在jQuery中)...
答案 0 :(得分:3)
我看到了三个问题:
您正在调用ready
两次(当您将函数传递给$()
时,就像将函数传递给$(document).ready()
)。这在很大程度上是无害的,但完全没有必要。
按钮上id
的属性与下一个按钮相撞;浏览器可能会忽略它:
<input type ="button" id = "sb"value="Create Account"/>
<!-- ^^^^^^^^^ -->
(如果需要,可以在=
周围留出空格,但将"sb"
撞到value
可能无效。)
(可能偏离主题,可能不是):你似乎(从引用的代码中)成为The Horror of Implicit Globals的牺牲品。您应该声明getmessage
变量。
所以:
<script>
$(document).ready(function(){
// Removed the unnecessary `$(function() { ...` here and the matching closing bits at the end
$("#sb").click(function(e){
e.preventDefault();
var getmessage = "Yes"; // <== Added `var`
getmessage = encodeURIComponent(getmessage);//url encodes data
$.ajax({
type: "POST",
url: "get_login.php",
data: {'getmessage': getmessage},
dataType: "json",
success: function(data) {
$("#message_ajax").html("<div class='successMessage'>" + data.message +"</div>");
}
});
});
});
</script>
和
<input type="button" id="sb" value="Create Account"/>
答案 1 :(得分:2)
你的HTML不好:
<p>><input type ="button" id = "sb" value="Create Account"/></p>
应该是
<p><input type ="button" id="sb" value="Create Account"/></p>