开发者

confusion over simple variable declaration jQuery "$variable" vs javascript "var"

I have this simple ghost text implementation:

HTML code:

<div id="searchPanel">
     <form method="get" id="searchBox" action="somePage.php">
     <input class="ghText" type="text" name="query" value="search here"/>
     </form>
</div>

jQuery code:

$(document).ready(function(){
        $txtField = "#searchPanel form input.ghText";
        var value = $($txtField).val();
        $($txtField).focus(function(){
            if($(this).val() == value)
                $(this).val("").removeClass("ghText");
        });
        $($txtField).blur(function(){
            if($(this).val()==""){
                $(this).val(value).addClass("ghText");
            }
        });
});

The example above is not going to work. When the user focuses the cursor on the search bar, the class "ghText" wont be removed for some reason.

However now if I change the "var value" (variable initialization) and "value" with "$value" as in:

$value = $($txtField).val(); 
$(this).val($value).removeClass("ghText");
$(this).val($value).addClass("ghText");

everything works perfectly.

I can just go to sleep and not worried too much about it..but I am very curious why something like that can happe开发者_如何转开发n?

is it because of the "this" not referreing to the right object, or is it because i tried storing jQuery object in non-jQuery variable or is it about something else..can somebody point out to me what was wrong? I have always thought that "var x" is the same as "$x"..?


You seem to be confused about JavaScript variables. There is no such thing as "jQuery variables" and "non-jQuery variables". Some specific cases:

  • A variable declared with var is different to a variable without. "var x" is a local variable, so it will not share a value with other functions which also have a variable called "x". This is almost always a good thing, so you should almost always declare variables with "var".
  • The $ in jQuery is sort of special. It isn't that special; it's just that jQuery has declared a variable called "$" which does some fancy operations.
  • There is nothing special about variables that begin with "$". In other words, "$x" is just a variable name. It is a different variable to "x", and it isn't a "jQuery variable". It's just a JavaScript variable called "$x". (This is different from PHP, where the $ is actually a special variable syntax.)

So you can just call it "value" instead of "$value".

Possibly the fact that you removed the "var" changed things by making it into a global variable.

As for "this", yes, that is a tricky aspect of JavaScript, and might be causing your problem. The value of "this" inside the inner 'focus' and 'blur' functions is likely to be different from the value of "this" outside. I'm not sure exactly what "this" refers to in an event handler, but it will not be the same object. So what you probably want to do is assign "this" to a variable in the outer function, and then refer to that variable on the inside in place of "this".


When storing a jQuery selection in a variable, it's common practice to add a $ before the variable name like this:

var $banner = $('#banner');

It's not necessary to include the dollar sign — var banner = $('#banner') would work just as well. However, the dollar sign reminds you that the variable holds a jQuery selection and not just any value like a number or a string.


@mgiuca is entirely right about Javascript variables - the '$' that precedes them is just a naming convention that most use to identify jQuery objects. I add this because you say

because i tried storing jQuery object in non-jQuery variable

but this is wrong. $txtField is a string that you are using to select an object. If you want to store the object itself you should do $txtField = $(#searchPanel form input.ghText) and then use it thusly $txtField.val().

Having said that your code works fine for me unaltered. I've set up a demo which works on Chrome - is this a cut down version of you code?


In to addition @mgiuca's answer here is a little more elaborate approach to your problem that also shows some of the jQuery concep:

$(document).ready(function () { 
  // define two helper functions
  var removeDefault = function () {
    if( $(this).val() == $(this).data("defaultValue") ) {
      $(this).val("").removeClass("ghText");
    }
  };
  var setDefault = function () {
    if( $(this).val() == "" ) {
      $(this).val( $(this).data("defaultValue") ).addClass("ghText");
    }
  };
  // the following works on all input elements
  $("#searchPanel form input.ghText").each(function () {
    $(this)
    .data("defaultValue", $(this).val())
    .focus(removeDefault)
    .blur(setDefault);
  });
}); 

Note

  • the use of .data() to associate a value with a specific element.
  • the use of .each() to apply the same behavior to any number of elements
  • the use function references for .focus() and .blur() - jQuery will always set the this correctly on its own
  • see it working over here http://jsfiddle.net/xsXxn/


So $x is a jQuery variable after all :) ... Well, anyway, here is one instance when $ or not $ did make a big difference in my code:

...load("whatever.php", {par1: var1, par2: var2})

didn't work, at least inside the $(obj).attr() assignment, unless $var1, $var2 where used. This worked:

$(obj).attr("onClick",$("#wherever").load("whatever.php", {par1: $var1, par2: $var2})...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜