jquery - elem.nodeName 返回未定义,jQuery 中的错误?

标签 jquery validation

目前,我正在修改注册页面以使用 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/

相关文章:

jQuery 插件 : Validation- labels are getting hidden

javascript - 选择-选择多选 - 根据第一个的 selected.count 禁用第二个选择

java - 自定义注释验证在 spring 中不对 @pathParam 进行验证

asp.net - 可以从 jQuery 触发 asp.net 验证吗?

javascript - 使用通过自定义数据属性检索的选择器在音频播放时显示目标 div

javascript - 多个错误 DIV 的 JQuery 错误放置

ruby-on-rails - Rails对模型属性的大于验证模型

Javascript - 添加后删除行

jquery - 如何在 Jquery 中显示/隐藏 2 个以上的跨度类并在它们之间切换?

javascript - 如何获取 jQuery 中所有子元素的所有(不同)类名?