2012-11-04 32 views
1

我有一个循环:jQuery的追加()对循环之后的多个元素无需压缩到HTML

for (index = 0; index < total_groups; index += 1) { 

    groups[index].list_item = $(list_item_snippet); 

    // Closure to bind the index for event handling 
    (function (new_index) { 

     groups[index].list_item.find('.listing-group-title') 
           .html(groups[index].Group.Name) 
           .click(function(e){ 

      fns.manageActiveGroup(new_index, groups); 
      return false; 
     }); 

    })(index); 

    // Append to DOM 
    mkp.$group_listing.append(groups[index].list_item); 
}; 

我宁愿不叫append()每次循环火灾。

我知道我可以使用一个字符串并将标记与每个循环迭代连接起来,并在末尾附加字符串mkp.$group_listing,但这会使对象变平并且绑定丢失(我不依赖于ID)。

有没有办法将我的对象添加到数组中,并将它们全部追加到底部,而不会翻译成HTML?

假设:

  • $(list_item_snippet)包含一些HTML定义一个列表项(并且包括具有.listing-group-title类的元素)。
  • groups是JSON在我的脚本定义一个“基团”一个块
  • 封闭工作完全

编辑:

发现我可以使用以下句法来追加多个元素:

mkp.$group_listing.append(groups[0].list_item, groups[1].list_item); 

但我显然需要自动化它 - 它不是一个数组它只是可选的附加函数参数,所以我不知道该怎么做秒。

+0

你如何约束事件?在'manageActiveGroup(...)里面''? – techfoobar

+0

在代码片段中向右滚动;) - 对不起,应该重新格式化。 – Alex

+0

@Alexcoady你需要看到我的答案 - 它解决了你的编辑问题。 – Alnitak

回答

4

要追加要素来选择一个数组,你可以这样做:

$.fn.append.apply($sel, myArray); 

在你的情况,因为它实际上是.list_item您需要的每个阵列元素的属性可以使用$.map来首先提取那些元素:

$.fn.append.apply(mkp.$group_listing, $.map(groups, function(value) { 
    return value.list_item; 
})); 
+0

明智的答案,并很好地解释。非常感激! – Alex

0

而不是将其绑定你做,如果你将它绑定使用on()像下面的方式,

$(document).on('click', '.listing-group-title', function() { 
    // click handler code here 
}); 

您可以拼合HTML和在一个声明中追加它,它还是会正常工作。

注:为了更好的效率,在上面的语句选择匹配的.listing-group-title

+0

但是在这种情况下点击任何'.listing-group-title'会触发相同的事件。我的循环将不同的变量值传递给click处理函数。任何导航元素都会触发我认为的最后一个索引。 – Alex

0

是最接近父更换document。使用jQuery add方法将所有项目添加到jQuery对象。然后追加那个对象。

http://api.jquery.com/add/

编辑:例:

var arr = $(); 

for (index = 0; index < total_groups; index += 1) { 

    groups[index].list_item = $(list_item_snippet); 

    // Closure to bind the index for event handling 
    (function (new_index) { 
     ... 
    })(index); 

    // Add to jQuery object. 
    arr.add(groups[index].list_item)); 
}; 

mkp.$group_listing.append(arr); 
+0

不幸的是,这并没有奏效。 – Alex

+0

循环结尾的'arr'的值是'[]' – Alex