开发者

Similar jQuery functions not firing keyup() more than once

I have a few JavaScript functions that all look similar to me. but behave differently to how I want them to.

I would like another element to be updated with some text when the value of the input has been evaluated. However for code re-useability I would like to pass the element to be updated to the function, but when I do this the keyup() event will not fire when text is typed into the input box.

Why is this?

Here is the one that works, but I have so specify the element to be开发者_如何转开发 updated explicitly.

Keyup Working

$(function(){ 
     $("#form1").keyup(function(){
         var val = $(this).val();
         if(val.length < 5){
             $("#inputFeedback").html("Less then 5 chars");
         }else{
             $("#inputFeedback").html("More then 5 Chars!");
     }
});

Here is what I would like to do but the keyup() event will not work on.

Keyup Not working

var validate = function(feedback){
   var val = $(this).val();
   if(val.length < 5){
       $(feedback).html("Less then 5 chars");
   }else{
       $(feedback).html("More then 5 Chars!");
   }
}


$(function(){
    $("#form1").keyup(validate($("#inputFeedback")));
});

Note: I have also tried as arguments $(this) and "#inputfeedback" to no avail!

I have also tried to use classical JavaScript function foo(bar){ ... } type functions but this has the same effect as the last example above.

I am sure it is something I am not doing right or understanding here but after a good few hours of searching and reading I can't find anything to help me with this one!


You definitely can't do callbacks like that:

http://docs.jquery.com/How_jQuery_Works#Wrong


var validate = function(feedback){
  var val = $(this).val();

  if(val.length < 5){
    $(feedback).html("Less then 5 chars");
  }else{
    $(feedback).html("More then 5 Chars!");
  }
}


$(function(){
  $("#form1").keyup(function(){
    validate.call(this, '#inputFeedback');
  });
});

or

var validate = function(feedback){
  return function(){
    var val = $(this).val();

    if(val.length < 5){
      $(feedback).html("Less then 5 chars");
    }else{
      $(feedback).html("More then 5 Chars!");
    }
  }
}


$(function(){
  $("#form1").keyup(validate('#inputFeedback'));
});


Try writing it this way:

var feedback=$("#inputFeedback");
$("#form1").keyup(validate(feedback));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜