简体   繁体   English

存储对此jquery对象的引用的正确方法是什么?

[英]What is the correct way to store a reference to this jquery object?

Say, I want to grab a reference to several elements, I use a selector like this: 说,我想获取对几个元素的引用,我使用如下选择器:

$(input) ... and then do something with it $(input) ...然后对其进行处理

But if I want to keep that reference, which one of these is the proper way? 但是,如果我想保留该参考,哪种方法是正确的?

var el = $('input');

$el = $('input');

Thanks 谢谢

var el = $(input); // Creates a local variable el //创建一个局部变量el

$el = $(input); // Creates a global variable $el //创建一个全局变量$el

$ does nothing special but var $除了var没什么特别的

Using $ at staring of variable name is just a convention to signify the variable is not ordinary variable but a jQuery object (or a collection of jQuery objects). $标记变量名只是一个约定,表示该变量不是普通变量,而是jQuery对象(或jQuery对象的集合)。 Its not compulsory but a good habit. 它不是强制性的,而是一种好习惯。

But, if you wont put var , it will make the variable global. 但是,如果您不放var ,它将使变量成为全局变量。

this will do that task for you 这将为您完成这项任务

$('a').click(function() {
    var $anchor = $(this);
    //var anchor = $(this);
    $anchor.fadeOut();
    //anchor.fadeOut();
})

Either 要么

var el = $(input);

or 要么

var $el = $(input);

Always use var . 始终使用var Using a $ sign before the variable name is just something some people do to signify that it is a jQuery object, it's not necessary but can be useful in making your code more readable. 在变量名之前使用$符号只是为了表明它是jQuery对象而做的事情,这不是必需的,但对于使代码更具可读性很有用。

Both are correct but difference is as below, 两者都是正确的,但区别如下

var el = $(input); this will create variable and assign value to it. 这将创建变量并为其赋值。

$el = $(input); this will assign value to previously defined variable in global or local scope. 这将为globallocal范围内的先前定义的变量赋值。

it all depends... example 这一切都取决于...示例

function A() {
    var $el = $(input);
    function B() {
        $el = $(input2);
    }

    // $el here is $(input2)
} 

function C() {
    var $el = $(input);
    function D() {
        var $el = $(input2);
    }

    // $el here is $(input)
} 

it all depends on your scope... so plan well... 这一切都取决于您的范围...所以要做好计划...

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

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