2010-08-06 110 views
0

比方說,我們有這個不明 DIVjQuery的.append(函數(指數,HTML){...})問題

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

,我們希望把後馬上包含幾十個其他不明DIV或幾百SPAN元素:

<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()方法調用中,那麼函數在值數組的每次迭代中都必須做些什麼SPAN並將該跨度注入容器中?

感謝

回答

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

+0

謝謝,jAndy。這個建議很有幫助,但是在創建對$ ctn的引用時,您正在迴避這個問題/問題:我想知道是否可以僅使用鏈接方法來完成此操作。 – Tim 2010-08-06 14:13:36