confusion over simple variable declaration jQuery “$variable” vs javascript “var”

后端 未结 5 1963
被撕碎了的回忆
被撕碎了的回忆 2020-12-04 15:48

I have this simple ghost text implementation:

HTML code:

5条回答
  •  一整个雨季
    2020-12-04 16:21

    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".

提交回复
热议问题