简体   繁体   English

对简单变量声明 jQuery “$variable” 与 javascript “var” 的混淆

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

I have this simple ghost text implementation:我有这个简单的幽灵文本实现:

HTML code: HTML 代码:

<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: jQuery 代码:

$(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.当用户将 cursor 聚焦在搜索栏上时,class “ghText”不会因为某种原因被删除。

However now if I change the "var value" (variable initialization) and "value" with "$value" as in:但是,现在如果我用“$value”更改“var value”(变量初始化)和“value”,如下所示:

$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 happen?我可以只是 go 睡觉而不用太担心它..但我很好奇为什么会发生这样的事情?

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?是因为“this”没有引用正确的 object,还是因为我尝试将 jQuery object 存储在非 jQuery 变量中,或者是其他什么问题? I have always thought that "var x" is the same as "$x"..?我一直认为“var x”和“$x”是一样的..?

You seem to be confused about JavaScript variables.您似乎对 JavaScript 变量感到困惑。 There is no such thing as "jQuery variables" and "non-jQuery variables".没有“jQuery 变量”和“非 jQuery 变量”之类的东西。 Some specific cases:一些具体案例:

  • A variable declared with var is different to a variable without.使用var声明的变量与没有声明的变量不同。 "var x" is a local variable, so it will not share a value with other functions which also have a variable called "x". “var x”是一个局部变量,因此它不会与其他也有一个名为“x”的变量的函数共享一个值。 This is almost always a good thing, so you should almost always declare variables with "var".这几乎总是一件好事,所以你几乎应该总是用“var”声明变量。
  • The $ in jQuery is sort of special. jQuery 中的 $ 有点特殊。 It isn't that special;那么特别。 it's just that jQuery has declared a variable called "$" which does some fancy operations.只是 jQuery 声明了一个名为“$”的变量,它执行了一些花哨的操作。
  • There is nothing special about variables that begin with "$".以“$”开头的变量没有什么特别之处。 In other words, "$x" is just a variable name.换句话说,“$x”只是一个变量名。 It is a different variable to "x", and it isn't a "jQuery variable".它是与“x”不同的变量,它不是“jQuery 变量”。 It's just a JavaScript variable called "$x".它只是一个名为“$x”的 JavaScript 变量。 (This is different from PHP, where the $ is actually a special variable syntax.) (这与 PHP 不同,其中 $ 实际上是一种特殊的变量语法。)

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.可能您删除“var”这一事实通过将其变为全局变量而改变了事情。

As for "this", yes, that is a tricky aspect of JavaScript, and might be causing your problem.至于“这个”,是的,这是 JavaScript 的一个棘手方面,可能会导致您的问题。 The value of "this" inside the inner 'focus' and 'blur' functions is likely to be different from the value of "this" outside.内部“焦点”和“模糊”函数内部的“this”值可能与外部“this”的值不同。 I'm not sure exactly what "this" refers to in an event handler, but it will not be the same object.我不确定事件处理程序中的“this”到底指的是什么,但它与 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".因此,您可能想要做的是将“this”分配给外部 function 中的变量,然后在内部引用该变量来代替“this”。

When storing a jQuery selection in a variable, it's common practice to add a $ before the variable name like this:在变量中存储 jQuery 选择时,通常的做法是在变量名称前添加$ ,如下所示:

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

It's not necessary to include the dollar sign — var banner = $('#banner') would work just as well.不必包含美元符号 - var banner = $('#banner')也可以。 However, the dollar sign reminds you that the variable holds a jQuery selection and not just any value like a number or a string.但是,美元符号提醒您该变量包含 jQuery 选择,而不仅仅是数字或字符串等任何值。

@mgiuca is entirely right about Javascript variables - the '$' that precedes them is just a naming convention that most use to identify jQuery objects . @mgiuca 关于 Javascript 变量是完全正确的——它们前面的“$”只是一个命名约定,大多数用于标识jQuery 对象 I add this because you say我添加这个是因为你说

because i tried storing jQuery object in non-jQuery variable因为我尝试将 jQuery object 存储在非 jQuery 变量中

but this is wrong.但这是错误的。 $txtField is a string that you are using to select an object. $txtField是您用于 select 和 object 的字符串。 If you want to store the object itself you should do $txtField = $(#searchPanel form input.ghText) and then use it thusly $txtField.val() .如果你想存储 object 本身,你应该这样做$txtField = $(#searchPanel form input.ghText)然后使用它$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?我已经设置了一个可以在 Chrome 上运行的演示- 这是你代码的精简版吗?

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:所以 $x 毕竟是一个 jQuery 变量:)...好吧,无论如何,这是一个例子,当 $ 或不 $ 确实对我的代码产生很大影响时:

...load("whatever.php", {par1: var1, par2: var2}) ...加载(“whatever.php”,{par1:var1,par2:var2})

didn't work, at least inside the $(obj).attr() assignment, unless $var1, $var2 where used.至少在 $(obj).attr() 分配中不起作用,除非使用了 $var1, $var2 。 This worked:这有效:

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

In to addition @mgiuca's answer here is a little more elaborate approach to your problem that also shows some of the jQuery concep:除了@mgiuca's answer here之外,还有一个更详细的方法来解决您的问题,它也显示了一些 jQuery 概念:

$(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.使用.data()将值与特定元素相关联。
  • the use of .each() to apply the same behavior to any number of elements使用.each()将相同的行为应用于任意数量的元素
  • the use function references for .focus() and .blur() - jQuery will always set the this correctly on its own使用 function 引用.focus().blur() - jQuery 将始终自行this设置
  • see it working over here http://jsfiddle.net/xsXxn/看到它在这里工作http://jsfiddle.net/xsXxn/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM