jQuery .append(function(index,html){...})问题

时间:2010-08-06 12:34:38

标签: jquery html append populate

假设我们有未识别的 DIV

  <div class="class-occurs-many-times-on-page">foo</div>

我们希望在它之后放置另一个包含数十个或数百个SPAN元素的未识别DIV:

<div class="a-class-that-occurs-many-times-on-page">foo</div>
<div class="another-class-that-occurs-many-times-on-page">
        <span class="latin">lorem</span><span class="latin">ipse</span>
        <span class="swedish-chef">føø</span><span class="swedish-chef">bår</span>
        .
        .
        .
        <span>...</span>
</div>

我们添加了第一个未识别的DIV,并希望以这种方式添加SPAN容器DIV:

 values = [{word: "lorem", cls: "latin"}, {word: "ipse", cls: "latin"},
 {word:"føø",cls:"swedish-chef"}, {word:"bår",cls:"swedish-chef"}];

 $("#" +  someParentElement).append(
     $("<div></div>").addClass("a-class-that-occurs-many-times-on-page").text("foo").after(

            $("<div></div>").addClass("another-class-that-occurs-many-times-on-page").append(
                 function(index, html){                    
                     // how to wrap each value in the values array in a span
                     // and inject each of those spans into this DIV?

                 }
            )

      )


 );

这种方法是否可行,如果是这样,那么.append()方法调用中的函数必须对values数组的每次迭代执行什么操作,如果目标是将数组中的每个值包装在一个SPAN并将该跨度注入容器?

由于

1 个答案:

答案 0 :(得分:0)

values = [{word: "lorem", cls: "latin"}, {word: "ipse", cls: "latin"}, {word:"føø",cls:"swedish-chef"}, {word:"bår",cls:"swedish-chef"}],
len    = values.length,
$ctn   = $('<div/>', {
     class:   'another-class-that-occurs-many-times-on-page'
}),
buildarr = [];

while(len--){
    buildarr.push('<span>');
    buildarr.push(values[len].word);
    buildarr.push(values[len].cls);
    buildarr.push('</span>');
}

$ctn.append(buildarr.join('')).appendTo(document.body);

这只是一个建议,就像你可以完成那样的任务。它假定我们必须填充数组的顺序是无关紧要的(通过以最快的方式循环reversed while)。如果订单很重要,请使用standard for loop