简体   繁体   English

jQuery附加到jQuery变量而不是DOM元素

[英]jQuery append to jQuery variable instead of DOM element

Is it possible to append to jQuery variable? 是否有可能附加到jQuery变量?

someting like this $($tnail).appendTo($collection); 喜欢这个$($tnail).appendTo($collection);

I need to optimize costly DOM modifications and want to do it all at once. 我需要优化昂贵的DOM修改并希望一次完成所有操作。

something like this: 这样的事情:

    var $collection;

 $.each(items, function (i, item) {

        var $tnail = $("<div></div>");

        $($tnail).appendTo($collection);

    });

    $($collection).appendTo("#Container");

Yes! 是! You just need to make sure $collection is a jQuery object: 您只需要确保$collection是一个jQuery对象:

var $collection = $('<x/>');

$.each(items, function (i, item) {

    var $tnail = $("<div></div>");

    $tnail.appendTo($collection);

});

$($collection.html()).appendTo("#Container");

You've also got 2 bits where you wrap a jQuery object in a new jQuery call: $tnail is already a jQuery wrapped div, so it already has the appendTo method. 在新的jQuery调用中,你还有2位包装jQuery对象: $tnail已经是一个jQuery包装的div,所以它已经有了appendTo方法。 Even more performance benefits! 更多性能优势!

EDIT: As Kevin points out, you can't append to an empty jQuery object. 编辑:正如Kevin指出的那样,你不能附加到一个空的jQuery对象。 Internally, jQuery uses empty document fragments, but it doesn't expose this through it's API. 在内部,jQuery使用空文档片段,但它不会通过它的API公开它。 So I've change my solution to create a dummy element, and then only append its contents to #Container . 所以我改变了我的解决方案来创建一个虚拟元素,然后只将其内容附加到#Container

You don't actually want to append the elements to $collection, you want to add them to it. 您实际上并不想将元素追加到$ collection,而是希望将它们添加到$ collection中。

var $collection = $(); // must be a jquery object
$.each(items, function (i, item) {

    var $tnail = $("<div></div>");

    // add to collection
    $collection.add($tnail);

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM