编辑:从jQuery 1.4开始,使用 $()将按照以下说明运行。
Edit: As of jQuery 1.4, using $() will work as described below.
我需要遍历一个数组并创建一些我想要的元素一个jQuery结果对象。
I need to loop through an array and create a number of elements which I want to have in a single jQuery result object.
for (var i = 0; i < 10; ++i) { $myJQueryObj = $myJQueryObj.add($("<span>blahblah</span>")); }然而,问题在于你需要一个jQuery对象来开始有了,你显然想把它弄空。在上面的示例中,我应该如何初始化 $ myJQueryObj ?
The problem with this, however, is that you need a jQuery object to begin with, and you obviously want to start it empty. In the above example, how should I initialise $myJQueryObj ?
以下示例不起作用,因为它们全部选择文档对象:
The following examples do not work, as they all select the document object:
$('') $() $(null) $(false)这些确实有效......但......
These do work... but...
$('#nonExistantElement') // yuck $().slice(0,0) // surely there's a nicer way?有更好的方法吗?
推荐答案是的。尝试 $([])。 $()的原因不起作用是因为jQuery需要一个上下文,并且没有任何提供,将默认为 document 作为上下文。很多事情都依赖于这个假设是正确的,所以改变 $()意味着给我空集将充其量只是问题。
Yep. Try $([]). The reason $() doesn't work is because that jQuery expects a context, and without any supplied, will default to document as the context. Many things depend on this assumption being true, so changing $() to mean "give me the empty set" would be problematic at best.
更多推荐
如何创建一个空的jQuery结果
发布评论