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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6288649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:07:52  来源:igfitidea点击:

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

javascriptjquery

提问by Benny Tjia

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.

上面的例子是行不通的。当用户将光标聚焦在搜索栏上时,由于某种原因,类“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?

我可以去睡觉而不用太担心它..但我很好奇为什么会发生这样的事情?

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

是因为“this”不是指正确的对象,还是因为我尝试将 jQuery 对象存储在非 jQuery 变量中,或者是因为其他事情..有人能指出我出了什么问题吗?我一直认为“var x”和“$x”是一样的..?

回答by mgiuca

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

您似乎对 JavaScript 变量感到困惑。没有“jQuery 变量”和“非 jQuery 变量”之类的东西。一些具体案例:

  • A variable declared with varis different to a variable without. "var x" is a localvariable, 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 thatspecial; 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.)
  • 使用var声明的变量与不使用var声明的变量不同。"var x" 是一个局部变量,因此它不会与其他函数共享一个值,这些函数也有一个名为 "x" 的变量。这几乎总是一件好事,所以你几乎总是应该用“var”声明变量。
  • jQuery 中的 $ 有点特殊。没有那么特别;只是 jQuery 声明了一个名为“$”的变量,它执行一些奇特的操作。
  • 以“$”开头的变量没有什么特别之处。换句话说,“$x”只是一个变量名。它是与“x”不同的变量,它不是“jQuery 变量”。它只是一个名为“$x”的 JavaScript 变量。(这与 PHP 不同,其中 $ 实际上是一种特殊的变量语法。)

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

所以你可以称它为“value”而不是“$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. 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".

至于“这个”,是的,这是 JavaScript 的一个棘手方面,可能会导致您的问题。内部“focus”和“blur”函数中“this”的值可能与外部“this”的值不同。我不确定“this”在事件处理程序中究竟指的是什么,但它不会是同一个对象。因此,您可能想要做的是将“this”分配给外部函数中的变量,然后在内部引用该变量来代替“this”。

回答by alice

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. However, the dollar sign reminds you that the variable holds a jQuery selection and not just any old value like a number or a string.

没有必要包含美元符号var banner = $(‘#banner')——也可以。然而,美元符号提醒您,该变量包含一个 jQuery 选择,而不仅仅是像数字或字符串这样的任何旧值。

回答by Stuart Burrows

@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

@mgiuca 关于 Javascript 变量是完全正确的 - 在它们之前的 '$' 只是一个命名约定,最常用于标识jQuery 对象。我添加这个是因为你说

because i tried storing jQuery object in non-jQuery variable

因为我尝试将 jQuery 对象存储在非 jQuery 变量中

but this is wrong. $txtFieldis 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().

但这是错误的。$txtField是用于选择对象的字符串。如果你想存储对象本身,你应该这样做$txtField = $(#searchPanel form input.ghText),然后这样使用它$txtField.val()

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

话虽如此,您的代码对我来说没有改变就可以正常工作。我已经建立了一个适用于 Chrome的演示- 这是你代码的简化版本吗?

回答by Tomalak

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 的回答是针对您的问题的更详细的方法,该方法还显示了一些 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.
  • 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 thiscorrectly on its own
  • see it working over here http://jsfiddle.net/xsXxn/
  • 使用.data()将值与特定元素相关联。
  • 使用.each()将相同的行为应用于任意数量的元素
  • 对于使用功能的引用.focus().blur()- jQuery将始终设置this正确地对自己
  • 看到它在这里工作http://jsfiddle.net/xsXxn/

回答by Nika Tsilosani

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})

...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() 赋值中,除非使用了 $var1, $var2。这有效:

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

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