如何创建一个空的jQuery结果 [英] How to create an empty jQuery result

查看:75
本文介绍了如何创建一个空的jQuery结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


编辑:从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结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆