for循环之后的多个元素的jQuery append(),而不是展平为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()
。
我知道我可以使用String并将标记与每个循环迭代连接mkp.$group_listing
并在最后将字符串附加到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 );
但我显然需要自动化它 – 它不是一个数组,它只是可选的附加function参数,所以我不知道如何做到这一点。
要将一个元素数组附加到选择器,您可以使用:
$.fn.append.apply($sel, myArray);
在您的情况下,因为它实际上是您需要的每个数组元素的.list_item
属性,您可以使用$.map
首先提取它们:
$.fn.append.apply(mkp.$group_listing, $.map(groups, function(value) { return value.list_item; }));
如果你使用on()
绑定它,而不是像你完成的那样绑定它,
$(document).on('click', '.listing-group-title', function() { // click handler code here });
您可以展平HTML并将其附加到一个语句中,它仍然可以工作。
注意:为了提高效率,请将上述语句中的document
替换为与.listing-group-title
最近的父级匹配的选择器
是。 使用jQuery add
方法将所有项添加到jQuery对象。 然后附加一个对象。
编辑:示例:
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);