$变量前面的含义是什么?

Ric*_*d77 3 jquery

(this)前面的$ dollar符号用于选择当前元素.我对选项和thisSelect前面的$有点困惑.他们有特殊意义吗?

var $options = $(this).children('option');
var $thisSelect = $(this);
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助

Ani*_*nil 9

正如大家所说,它只是一个惯例.
我使用$变量前面的符号来标识此变量包含对象.

var thisIsANumber = 1024; // No $.. Its a normal variable
var $divElement = $('div#idOfDiv'); // Yes! Its a jQuery Object
var $this = $(this); // Commonly used to reduce the work javascript has to do!

//Now I can use something like this.. (Notice how easy it is to read!)
$divElement.slideUp();

// Or a more `real world` example!
$('#element').click(function(){
    // Hold $(this) inside a variable
    // So we don't have to traverse the dom unnecessarily
    var $this = $(this); // Save it (its a object.. so prepend a `$` )
    $this.hide(); // Use it again
    $this.fadeIn(); // and again
//  ^ Has a dollar sign, because it is a jQuery Object.
});
Run Code Online (Sandbox Code Playgroud)

你会看到大量的插件使用这个约定(好吧......至少写得很好).
通过将对象存储在变量中,Javascript不必每次都能遍历代码来获取元素.相反,我们已经有了元素(在变量中),所以我们用它来引用它.

如果$(this)在同一个回调函数中使用多次,则应将其存储在变量..(var $this = $(this);)中.否则,每次使用它时,javascript都必须每次都从源代码中获取元素(这会大大降低性能!(特别是对于在慢/旧计算机上浏览的人!).


Iva*_*ova 5

它是jQuery包装对象的常见引用.它使得阅读代码更容易知道哪些变量是jQuery包装的.

//Item has been "cached" for later use in the script as a jQuery object.
var $item = $(this);
Run Code Online (Sandbox Code Playgroud)

其他常见做法:

如果变量是私有的,那么使用这样的下划线:

(function(){
     var _foo = "bar";
})()
Run Code Online (Sandbox Code Playgroud)

如果它是公开的,我们不使用下划线:

var foo = "bar"
Run Code Online (Sandbox Code Playgroud)

如果它是一个jQuery选择器,我们使用$:

var $foo = $('bar');    
//then you can access it like this
$foo.attr('id')
Run Code Online (Sandbox Code Playgroud)

它只是一个编码约定,它允许您快速引用变量稍后在代码中的类型.