javascript 创建一个空的 jQuery 对象:$({}) 或 $()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13149945/
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
Creating an empty jQuery object: $({}) or $()
提问by John Haldson
I have seen the following two variable initializations to create an empty jQuery object. Is there a major difference or advantage to use one over the other?
我已经看到以下两个变量初始化来创建一个空的 jQuery 对象。使用一个比另一个有很大的区别或优势吗?
var a = $({});
var b = $();
回答by josh3736
If you meant $([])
, that's something from the old days where calling $()
was actually equivalent to $(document)
(which was an undocumented feature). So to get an empty set, you'd have to call $([])
. This was changed in jQuery 1.4; the documented functionality of $()
is now to return an empty set.
如果您的意思是$([])
,那是过去呼叫$()
实际上等同于$(document)
(这是一个未记录的功能)的东西。所以要得到一个空集,你必须调用$([])
. 这在 jQuery 1.4中有所改变;$()
现在记录的功能是返回一个空集。
Passing objectsto the jQuery constructor is an entirely different beast. $({})
doesn't create an empty jQuery object. It creates a jQuery object with a length of 1; the selected item is the object itself.
将对象传递给 jQuery 构造函数是一种完全不同的野兽。 $({})
不会创建空的 jQuery 对象。它创建了一个长度为 1 的 jQuery 对象;所选项目是对象本身。
Passing JS objects to the jQuery constructor lets you take advantage of a more esoteric feature of jQuery: binding and triggering events on (non-DOM) objects.
将 JS 对象传递给 jQuery 构造函数可以让您利用 jQuery 更深奥的功能:在(非 DOM)对象上绑定和触发事件。
For example:
例如:
var obj = { some: 'stuff' };
$(obj).on('someevent', function() { ... });
$(obj).trigger('someevent');
Either way, if your goal is to instantiate a new, empty jQuery object, use $()
.
无论哪种方式,如果您的目标是实例化一个新的空 jQuery 对象,请使用$()
.
回答by elclanrs
I think you mean:
我想你的意思是:
var a = $([]); //<- array not object
var b = $();
No advantage that I know of, the first one is the old version, since 1.4 you can use the later.
没有我知道的优势,第一个是旧版本,因为1.4你可以使用后来的。