Javascript 用于for循环后的多个元素的jQuery append(),无需展平为HTML
我有一个循环:Javascript 用于for循环后的多个元素的jQuery append(),无需展平为HTML,javascript,jquery,optimization,loops,append,Javascript,Jquery,Optimization,Loops,Append,我有一个循环: 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
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);
};
但我显然需要将其自动化—它不是数组,只是可选的附加函数参数,因此我不确定如何实现这一点。如果您使用下面的方式绑定它,而不是像您所做的那样绑定它
$(document).on('click', '.listing-group-title', function() {
// click handler code here
});
您可以将HTML展平并附加到一条语句中,它仍然可以工作
注意:为了提高效率,请将上述语句中的文档替换为与列表组标题最接近的父项匹配的选择器,而不是像下面那样进行绑定
$(document).on('click', '.listing-group-title', function() {
// click handler code here
});
您可以将HTML展平并附加到一条语句中,它仍然可以工作
注意:为了提高效率,请将上述语句中的文档替换为与最接近的父项匹配的选择器。列表组标题是。使用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);
对。使用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);
要将元素数组附加到选择器,可以使用以下方法:
$.fn.append.apply($sel, myArray);
在您的情况下,由于它实际上是您需要的每个数组元素的.list_item属性,因此可以使用$.map首先提取这些属性:
$.fn.append.apply(mkp.$group_listing, $.map(groups, function(value) {
return value.list_item;
}));
要将元素数组附加到选择器,可以使用以下方法:
$.fn.append.apply($sel, myArray);
在您的情况下,由于它实际上是您需要的每个数组元素的.list_item属性,因此可以使用$.map首先提取这些属性:
$.fn.append.apply(mkp.$group_listing, $.map(groups, function(value) {
return value.list_item;
}));
您如何绑定这些事件?在manageActiveGroup内部?在代码段中向右滚动;-抱歉,应该重新格式化。@Alexcoady您需要查看我的答案-它解决了您的编辑问题。您如何绑定事件?在manageActiveGroup内部?在代码段中向右滚动;-抱歉,应该重新格式化。@Alexcoady您需要查看我的答案-它解决了您的编辑问题。但在这种情况下,单击任何。列表组标题将触发相同的事件。我的循环将不同的变量值传递给click处理程序函数。我认为,任何导航元素都会触发最后一个绑定索引。但在本例中,单击任何.listing组标题都会触发相同的事件。我的循环将不同的变量值传递给click处理程序函数。我认为,任何导航元素都会触发最后一个绑定索引。循环末尾的arr值为[],循环末尾的arr值为[],这是一个非常好的答案,解释得很好。非常感谢!回答得很好,解释得很好。非常感谢!