我想在循环中将一些html附加到一个空的非null jQuery对象,但它不起作用,除非我创建一个对象并在创建过程中添加一个html标记.如何创建一个空的jQuery对象,并能够在以后添加html?
//var $new = $().add(""); //can't use this object in the loop
//var $new = $([]); //can't use this object in the loop
//var $new = $(); //can't use this object in the loop
//var $new = $("#nonexistingelement"); //can't use this object in the loop
var $new = $().add("<tr>"); //works but I don't want to add any html at this point.
$.each(.....)
{
$new.append("<sometag>");
});
alert($new.html()); //should display some html
Run Code Online (Sandbox Code Playgroud)
增加: http ://jsfiddle.net/vfPNT /
编辑:从jQuery 1.4开始,使用
$()将如下所述工作.
我需要遍历一个数组并创建一些我希望在一个jQuery结果对象中拥有的元素.
for (var i = 0; i < 10; ++i) {
$myJQueryObj = $myJQueryObj.add($("<span>blahblah</span>"));
}
Run Code Online (Sandbox Code Playgroud)
但是,这个问题是你需要一个jQuery对象,你显然想把它开始为空.在上面的例子中,我该如何初始化$myJQueryObj?
以下示例不起作用,因为它们都选择了文档对象:
$('')
$()
$(null)
$(false)
Run Code Online (Sandbox Code Playgroud)
这些确实有效......但......
$('#nonExistantElement') // yuck
$().slice(0,0) // surely there's a nicer way?
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?
我想复制jquery对象选择,例如
当我选择多个对象时
var test = $(".someclass");
Run Code Online (Sandbox Code Playgroud)
我得到了具有该类的所有选定对象的对象.
现在我怎么能继续在那场战争中添加对象,比如说 test.push($(".somediv"));
我也看到了.add( jQuery object )但是Cannot call method 'add' of null
当我尝试将对象添加到空变量时它给了我错误
另外,如何创建没有值的jquery变量,然后再添加它们?