jQuery-如何将多个节点附加到容器 [英] jQuery - how to append multiple nodes to container

查看:147
本文介绍了jQuery-如何将多个节点附加到容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将多个节点附加到一个容器.我不想在每次迭代中进行缓慢的DOM附加,而是希望将文档片段中的节点排队(对其他想法开放),然后一次全部附加它们.这是我的代码:

I need to append multiple nodes to a container. Rather than doing a slow DOM append inside each iteration, I want to queue up the nodes in a document fragment (open to other ideas) and append them all at one time. Here is my code:

var fragment = document.createDocumentFragment();
$.each( poFailureInfoMultiple, function(i,e){
    fragment.appendChild(
         $('<button/>', {
            'class': 'el-contents-center multiple-record'
         })
    );
});

$('#some-container').html( fragment );

我的问题是我收到一条错误消息,指出:

My problem is I am getting an error message stating:

Could not convert JavaScript argument arg 0 [nsIDOMDocumentFragment.appendChild]

那么我如何一次将多个元素节点附加到我的DOM?我没有使用片段方法(我刚刚发现它,并且似乎可行).

So how can I append multiple element nodes to my DOM at once? I don't HAVE to use the fragment method (I just found it and it seemed viable).

注意: 我不想为该应用程序使用HTML语法

i.e. $('#some-container').append('<button class="myclass"></button>');

推荐答案

var elemsToAppend=$()

$.each( poFailureInfoMultiple, function(i,e){
    elemsToAppend = elemsToAppend.add(
        $('<button/>', {
            'class': 'el-contents-center multiple-record'
        })
    )
}); 
$('#some-container').append(elemsToAppend)

jQuery对象上的add方法不会更改对象本身,而是返回一个新对象,这就是为什么需要elemsToAppend = elemsToAppend.add(...)的原因.老实说,我不能说这种方法有多快.我实际上认为html方式虽然更快.

The add method on a jQuery object doesn't alter the object itself but returns a new object, which is why you need elemsToAppend = elemsToAppend.add(...). I honestly cant say how fast this method is though. I actually think the html way is faster though.

这篇关于jQuery-如何将多个节点附加到容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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