目前,我正在修改注册页面以使用 Ajax/jQuery。它处于简单阶段,仅要求输入用户名和密码。
我想使用 jQuery 告诉用户用户名文本框中的当前条目是否无效或已被使用。如果满足任一条件,div namemsg 将添加文本并执行 fadeIn 事件。
页面加载时提交按钮被禁用,通过验证后按钮被启用。为此,我有以下 ajax 请求来处理用户名验证
$("#username").keyup(function(){
//get current value
thisVal = $(this).val();
//execute request to see if current val exists in database
$.ajax({
type: "GET",
url: "includes/phpscripts.php?action=checkUser",
data: {username:thisVal},
success: function(data){
//if username is already taken, show warning and disable submit button
if (data == 'true'){
$("#namemsg").text("Username is already taken");
$("#namemsg").fadeIn(100);
$("#submit").attr('disabled', 'disabled');
}
//otherwise, possible valid username
else if (data == 'false'){
//check if username is of the proper length. If not, display
//error and disable submit button
if ($(this).val().length < 5){
$("#namemsg").text("Invalid Username");
$("#namemsg").fadeIn(100);
$("#submit").attr('disabled', 'disabled');
}
//valid username, enable submit button and hide any error messages
else {
$("#namemsg").hide();
$("#submit").removeAttr("disabled");
}
}
}
});
return false;
});
我的问题是请求从服务器获取了正确的值,但 firebug 提示 elem.nodeName
在 jquery 1.7.2 的第 2368 行未定义。该行是
if ( elem ) {
hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];
当我在 if (elem)
处设置断点时,elem
具有值
nodeName : INPUT
type : text
和hooks
返回未定义。这是 Firefox 特有的问题,还是我的代码或 jQuery 的问题?另外,有解决方法吗?
最佳答案
在您的 success
处理程序中,this
是 jqXHR 请求,而不是 $("#username")
字段,因此 $(this).val()
出错。
当您已经缓存了值时,最好使用 thisVal
而不是 $(this).val()
,但一般来说,方式是要解决此问题,请将 context
选项设置为元素;
$.ajax({
context: this,
type: 'GET',
// etc
});
您可以在jQuery.ajax()
上查看此方法的文档。页面(搜索“上下文”)。
您将看到的另一种方法是将指向该元素的 this
设置为另一个变量;
$("#username").keyup(function(){
var that = this;
$.ajax({
type: "GET",
url: "includes/phpscripts.php?action=checkUser",
data: {username:thisVal},
success: function(data){
// use `that` and `$(that)` in here
}
});
return false;
});
关于jquery - elem.nodeName 返回未定义,jQuery 中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11036017/