[英]What is the difference between $(var) and var?
It came to my understanding that you can use a DOM element as jQuery selector eg $(document)
. 据我了解,您可以将DOM元素用作jQuery选择器,例如
$(document)
。
So why does the jQuery attr()
function work in both these cases? 那么,为什么在这两种情况下jQuery
attr()
函数都起作用?
let v = $("#nodeID");
//First case
$(v).attr("href","www1"); //works
//Second case
v.attr("href","www2"); //also works
What's the difference? 有什么不同?
When you pass a jQuery object to $
, it will return a jQuery object containing the same elements as in the original jQuery object you passed. 当您将jQuery对象传递给
$
,它将返回一个jQuery对象,其中包含与您传递的原始jQuery对象相同的元素。 They're basically the same (though the objects are not ===
). 它们基本上是相同的(尽管对象不是
===
)。 You can nest jQuery objects in $
as much as you want, it won't make a difference, it's just odd to do. 您可以根据需要将jQuery对象尽可能多地嵌套在
$
中,这不会产生任何变化,这只是奇怪的事情。
$($($('div'))).text('foo');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div></div>
There are many different kinds of value you can pass to the jQuery function. 您可以将多种值传递给jQuery函数。 In this case you are passing a jQuery selection about which the documentation says:
在这种情况下,您将传递一个jQuery选择 ,文档中对此内容进行了说明:
selection
选择
Type: jQuery类型:jQuery
An existing jQuery object to clone.现有的要克隆的jQuery对象。
So you are cloning var
. 因此,您正在克隆
var
。
In this context, it is entirely pointless. 在这种情况下,这完全没有意义。 (It can be useful if you were going to mutate the value but needed to preserve the original to use elsewhere).
(如果您要更改值但需要保留原始值以在其他地方使用,则可能会很有用)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.