简体   繁体   English

Javascript / jQuery变量,使用var的正确方法是什么?

[英]Javascript/jQuery variable, what is the proper way to use a var?

I am sorry if this is a dumb or easy question but I am fairly new to Javascript/jQuery. 我很抱歉,如果这是一个愚蠢或简单的问题,但我对Javascript / jQuery相当新。 The past month I have really started to delve into the land of scripting and have seen two different, maybe three, ways people use var in Javascript/jQuery. 在过去的一个月里,我真的开始深入研究脚本领域,并且已经看到人们在Javascript / jQuery中使用var两种不同,也许是三种方式。

The way I use a var is like so, 我使用var的方式是这样的,

var nav = $('nav');

nav.hide();

A very common way I have seen people use vars, 我见过人们使用vars的一种非常常见的方式,

var nav = $('nav');

$(nav).hide();

From the answers, 从答案,

var $nav = $('nav');

$nav.hide();

From what I have learned from searching through Google is what you typed inside the variable is saved there to later be used. 从我通过Google搜索中学到的内容,您在变量中输入的内容将保存在那里以供日后使用。 I then figured if I wrote the $() around the var when I was using it, it would duplicate the $(). 然后我想到如果我在使用它时在var周围写了$(),它会复制$()。 Yet both ways seem to work so I know it does not duplicate it and therefore can tell that it is the same thing. 然而这两种方式似乎都有效,所以我知道它不会复制它,因此可以说它是一回事。

Is there a correct way to use vars or are both equally the same and it doesn't matter? 是否有正确的方法来使用vars或两者都是相同的并且无关紧要?

I apologize again if this is a known answer and will be happy to remove it if someone can show me the original question but I couldn't find anything on it. 如果这是一个已知的答案,我再次道歉,如果有人能告诉我原始问题但我找不到任何内容,我会很乐意将其删除。

A great bit of information from an answer that I didn't mark as the answer but I find to be very important. 从答案中得到的大量信息我并未将其标记为答案,但我认为非常重要。

var element = document.createElement("div");
$("body").append(element);
$(element).hide(); 

In the example above, $(element) is necessary, because it takes a DOM object and converts it to a jQuery selector. 在上面的示例中,$(element)是必需的,因为它接受DOM对象并将其转换为jQuery选择器。 jQuery functions only work on jQuery selectors, so you couldn't simply do element.hide(). jQuery函数只适用于jQuery选择器,所以你不能简单地做element.hide()。

$() creates a new jQuery object. $()创建一个新的jQuery对象。 If you save a jQuery object to a variable it is pointless to create another jQuery object from it, although it still works. 如果将jQuery对象保存到变量中,从它创建另一个jQuery对象是没有意义的,尽管它仍然有效。 You will often see people wrap variables that were previously created as jQuery objects in $() purely due to bad practice and either forgetting it's already an object...or not understanding what they just created in the first place 您经常会看到人们将以前在$()创建为jQuery对象的变量包装起来纯粹是因为不好的做法而忘记它已经是一个对象......或者不了解它们刚刚创建的对象

Perhaps you may have seen 也许你可能已经看过了

var $nav = $('nav');

$nav.hide();

Using the $ prefix is a common practice to denote that the variable is a jQuery object for code readability mostly 使用$前缀是一种常见做法,表示该变量主要是代码可读性的jQuery对象

Both variables store a jQuery object, which has access to jQuery methods. 这两个变量都存储了一个jQuery对象,该对象可以访问jQuery方法。 The latter approach unnecessarily tries to re-wrap that jQuery object in another jQuery object. 后一种方法不必要地尝试将jQuery对象重新包装在另一个 jQuery对象中。 The former approach is 'correct,' in that it's more efficient and less, to be frank, silly . 前一种方法是“正确的”,因为它更有效,更少,坦率, 愚蠢

I've seen this issue in a lot of places. 我在很多地方都看过这个问题。 People use a lot of $ when they don't need to. 人们在不需要时会使用大量的$。 Some use it just as an ornament on their variable name, which adds to the confusion. 有些人使用它作为变量名称的装饰,这增加了混乱。

First of all, there are no jQuery variables, only JavaScript variables, and as you said, variables store information. 首先,没有jQuery变量,只有JavaScript变量,正如你所说,变量存储信息。 When the right hand side begins with $(), you're storing the results of a jQuery function in the variable. 当右侧以$()开头时,您将jQuery函数的结果存储在变量中。 In the vast majority of cases, what you'll be storing is called a jQuery selector . 在绝大多数情况下,您将要存储的内容称为jQuery 选择器

In the case of var nav = $('nav') , what you're storing is a selector representing all the elements in the DOM that are nav tags, ie that look like <nav></nav> (or equivalent). var nav = $('nav') ,您要存储的是一个选择器,表示DOM中的所有元素都是导航标记,即看起来像<nav></nav> (或等效的)。

As others already mentioned, the $(nav) is taking the stored selector, and creating a new selector out of it. 正如其他人已经提到的那样, $(nav)正在获取存储的选择器,并从中创建一个新的选择器。 It accomplishes nothing and is redundant, and is a poor programming practice, even if it is a pervasive one. 它完成任何事情并且是多余的,并且是一种糟糕的编程实践,即使它是普遍存在的。

However, there is a similar syntax that makes sense: 但是,有一个类似的语法是有道理的:

var element = document.createElement("div");
$("body").append(element);
$(element).hide(); 

In the example above, $(element) is necessary, because it takes a DOM object and converts it to a jQuery selector. 在上面的示例中, $(element)是必需的,因为它接受DOM对象并将其转换为jQuery选择器。 jQuery functions only work on jQuery selectors, so you couldn't simply do element.hide() . jQuery函数只适用于jQuery选择器,所以你不能简单地做element.hide()

As I mentioned at the top, some people also use $ as a decorator on their variable names, eg var $selector = $("nav") . 正如我在顶部提到的,有些人还使用$作为变量名的装饰器,例如var $selector = $("nav") The $ on the left hand side means nothing - it's just a character in a variable name, but they use it as a convention to remind themselves that they're storing a jQuery selector. 左侧的$表示什么都没有 - 它只是变量名中的一个字符,但是它们使用它作为约定来提醒自己它们存储了一个jQuery选择器。 I'd avoid it, simply because it adds to the confusion, but it's out there, so I just wanted to mention it. 我会避免它,只是因为它增加了混乱,但它就在那里,所以我只是想提一下。

var is used to create any kind of variable. var用于创建任何类型的变量。 Could be var diceRoll = 4 or var myMessage = "Hello!" 可能是var diceRoll = 4var myMessage = "Hello!" , or anything else. 或其他任何东西。

$ is a function that jQuery provides, which behaves in different ways depending on what you pass to it. $是jQuery提供的一个函数,它根据您传递给它的内容以不同的方式运行。 For example, if you pass it a string (eg 'nav' ), it will find every nav element in the document and return a set of jQuery objects (elements) - one for each DOM element it finds. 例如,如果你传递一个字符串(例如'nav' ),它将找到文档中的每个nav元素并返回一组jQuery对象(元素) - 一个用于它找到的每个DOM元素。 When you say var nav = $('nav'); 当你说var nav = $('nav'); , you are assigning this set of jQuery objects to your nav variable, so you can work with it later. ,您将这组jQuery对象分配给nav变量,以便以后可以使用它。 So far so good. 到现在为止还挺好。

Instead of passing a string to $ , you technically could pass jQuery objects back into the $ function, which is what you are doing when you say $(nav).hide(); 你没有将字符串传递给$ ,而是技术上可以将jQuery对象传递回$函数,这就是当你说$(nav).hide();时你正在做的事情$(nav).hide(); . DOING THIS MAKES LITTLE SENSE - it will just return the same array of jQuery objects, nav , which you put into it in the first place!! 这样做会让人感觉不到 - 它会返回相同的jQuery对象数组, nav ,你首先放入它!

Personally, I like to prefix any variable which holds a jQuery object with a $ sign, ie var $nav = $('nav'); 就个人而言,我喜欢用任何带有$符号的jQuery对象的变量作为前缀,即var $nav = $('nav'); . This is just a convention that allows me to see at a glance that this variable holds a jQuery object (element) rather than a native DOM element, or integer, or so on. 这只是一个允许我一眼就看出这个变量包含jQuery对象(元素)而不是本机DOM元素或整数等的约定。 If I ever see $($myVar) in my code, I know it's probably time for bed... 如果我在代码中看到$($ myVar),我知道这可能是睡觉的时间......

Update: there are other things that it DOES make sense to pass into the $() function, apart from strings. 更新:除了字符串之外,还有其他一些事情可以传递到$()函数。 Passing in a DOM element, for example (such as saying $(document) ) creates a jQuery object representation of that DOM element, which can be very useful. 例如,传入DOM元素(例如说$(document) )会创建该DOM元素的jQuery对象表示,这可能非常有用。

All of these answers are pieces to the entire answer . 所有这些答案都是整个答案的一部分。 . . let me add yet another piece. 让我再添一块。 :) :)

As others have said, the $(...) notation is a JQuery function that returns a JQuery object. 正如其他人所说, $(...)表示法是一个返回JQuery对象的JQuery函数。 Depending on what "..." is, determines how that is done. 取决于“......”,确定如何完成。

Some examples: 一些例子:

  • if you put a selector, such as "div", in there, you will get a JQuery object that contains all of the DOM elements that match the selector pattern . 如果你在其中放置一个选择器,例如“div”,你将获得一个JQuery对象,其中包含与选择器模式匹配的所有DOM元素。 . . in this case, all of the <div> elements. 在这种情况下,所有<div>元素。

  • if you pass a string representation of an HTML element (eg, "<div></div>" ), you will get a JQuery object that points to a newly created <div> element. 如果传递HTML元素的字符串表示形式(例如, "<div></div>" ),您将获得一个指向新创建的<div>元素的JQuery对象。

  • if you put a DOM node reference in there (eg, one created by using document.getElementsByTagName("div") ), it will create a JQuery object that points to that node(s) in the reference. 如果你在那里放置DOM节点引用(例如,使用document.getElementsByTagName("div")创建的那个),它将创建一个指向引用中的节点的JQuery对象。

The whole point of this is that JQuery works with JQuery objects, so these various functions help programmers create them. 这一点的重点是JQuery与JQuery对象一起工作,因此这些各种函数可以帮助程序员创建它们。

Now this is where we get to your question . 现在,这是我们提出问题的地方。 . .

Each time you use $("...") , you are creating a brand new object, so, for example the following code will produce two unique JQuery objects, each of which pointing to the identical DOM elements: 每次使用$("...") ,您都在创建一个全新的对象,因此,例如,下面的代码将生成两个唯一的JQuery对象,每个对象都指向相同的DOM元素:

var $firstObject = $("div");
var $secondObject = $("div");

So, if you do a comparison of them (like this ($firstObject === $secondObject) ), they will not be seen as equal, because they are not the same object. 所以,如果你对它们进行比较(比如这个($firstObject === $secondObject) ),它们将不会被视为相等,因为它们不是同一个对象。

Now, let me do a slight variation of your second example to add a little more clarity. 现在,让我稍微改变你的第二个例子,以增加一点清晰度。 If you create a third variable and set it equal to the second one, like this: 如果您创建第三个变量并将其设置为等于第二个变量,如下所示:

var $thirdObject = $secondObject;

. . . you have two elements that are actually pointing to the same JQuery object, so they ARE actually equal (ie, ($secondObject === $thirdObject) will evaluate as true). 你有两个实际指向同一个JQuery对象的元素,所以它们实际上是相等的(即, ($secondObject === $thirdObject)将评估为true)。

Now finally, what you've shown with this peice of code: 最后,你用这段代码展示了什么:

$(nav).hide();

. . . is simply another example of trying to create a JQuery object . 只是尝试创建JQuery对象的另一个例子。 . . this time using another JQuery object. 这次使用另一个JQuery对象。 Doing this with that third variable that I created above, however, will now break the relationship that it has with the second variable . 但是,使用我在上面创建的第三个变量执行此操作现在将破坏它与第二个变量的关系。 . . ($secondObject === $($thirdObject)) . ($secondObject === $($thirdObject)) . . they are no longer equal, because the two sides of the comparison no longer point to the same object. 它们不再相等,因为比较的两面不再指向同一个对象。 Much like the comparison between $firstObject and $secondObject from earlier, that comparison is using two unique JQuery objects. 与前面的$firstObject$secondObject之间的比较非常相似,该比较使用了两个独特的JQuery对象。

However . 但是。 . .

Unlike some of the other answers, I would disagree that it is a completely incorrect form of coding . 与其他一些答案不同,我不同意这是一种完全不正确的编码形式。 . . while I would never use it in the situation that you provide in your example, passing a JQuery object into the $(...) function is essentially the same thing as using .clone() . 虽然我不会在你的例子中提供的情况下使用它,但是将JQuery对象传递给$(...)函数与使用.clone()基本相同。 The two $bar assignments below are functionally equivalent: 以下两个$bar分配功能相同:

var $foo = $("<div></div>");

var $bar = $($foo);
var $bar = $foo.clone();

The JQuery API even makes the same point ( http://api.jquery.com/jQuery/ ): JQuery API甚至提出了同样的观点( http://api.jquery.com/jQuery/ ):

Cloning jQuery Objects 克隆jQuery对象

When a jQuery object is passed to the $() function, a clone of the object is created. 将jQuery对象传递给$()函数时,会创建该对象的克隆。 This new jQuery object references the same DOM elements as the initial one. 这个新的jQuery对象引用与初始DOM元素相同的DOM元素。

EDIT : 编辑:

Out of curiosity, I set up a quick test at jsPerf and the $($foo) approach is pretty significantly faster than .clone() in Firefox, IE9, and Chrome: http://jsperf.com/clone-technique-test 出于好奇,我在jsPerf上设置了一个快速测试, $($foo)方法比Firefox,IE9和Chrome中的.clone()快得多: http.clone()

var nav = $('nav');

$(nav).hide();

nav is already a jQuery object so $(nav) is useless. nav已经是一个jQuery对象,因此$(nav)是无用的。

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

相关问题 在 HTML/Javascript 中使用计数器变量的正确方法 - Proper way to use a counter variable in HTML/Javascript 将jQuery与“ use strict”结合使用的正确方法是什么? - What's the proper way to use jQuery in conjunction with 'use strict'? map integer 到 Javascript 中其他变量的正确方法是什么 - What is proper way to map integer to other variable in Javascript 在javascript中测试对象是否是jQuery对象的正确/正确方法是什么? - What's the correct/proper way to test if an object is a jQuery object in javascript? 用jquery事件更新javascript中的主类的正确方法是什么? - What is the proper way to update main class in javascript with jquery events? <a>用Javascript / JQuery</a>替换` <a>`</a>的正确方法是<a>什么?</a> - What's the proper way to replace `<a>` using Javascript/JQuery? 在JavaScript“窗口”对象中存储变量是使用该对象的正确方法吗? - Storing a variable in the JavaScript 'window' object is a proper way to use that object? 在jQuery中将子选择器与上下文节点一起使用的新方法是什么? - What is the new proper way to use a child selector with a context node in jQuery? 在 angular js 指令中使用 jquery 的正确方法是什么? - what is proper way to use jquery in angular js directives? 在图像上使用JQuery的.load()的正确方法是什么? - What is the proper way to use JQuery’s .load() on an image?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM