【发布时间】:2015-04-05 19:59:06
【问题描述】:
在我的应用程序中,我将函数附加到具有集合类的元素:
$('.collection').each(initiateCollection);
function initiateCollection()
{
var $container = $(this).children('div:first-child');
if (!$container.data('is_collection'))
{
var $addButton = $container.children('.add_button').eq(0);
$addButton.on('click', function(e) {
addElement($container,index);
count++;
index++;
showHeaders($container, count);
correctSelect2Width($(this));
e.preventDefault();
return false;
});
var count = $container.find('.child_collection').length;
var index = $container.find('.child_collection').length;
console.log(count);
if (count == 0)
{
var $headers = $container.find('.headers').eq(0);
var $headerPrototype = $($container.attr('data-header'));
$headers.html($headerPrototype);
}
$container.on('click','.fmu_delete_button', function(e){
e.preventDefault();
var $row = $(this).closest('.row_to_delete');
$row.next('.sibling_row_to_delete').remove();
$row.next('.sibling_row_to_delete_2').remove();
$row.remove();
count--;
showHeaders($container, count);
});
showHeaders($container, count);
$container.data('is_collection', true);
}
}
问题是一些集合尚未加载,但我仍然需要它们的行为相同。我无法将该功能附加到单击上,并且焦点也无法直接工作:
$('body').on('focus', '.collection', initiateCollection);
上一行不起作用,因为我的集合默认/添加时没有立即获得焦点。我探索了其他解决方案但没有成功(当然我可以从添加集合的代码中重新绑定,但效率不高)。
我还能尝试什么?
【问题讨论】:
-
你能给我们举个例子吗?
-
为什么你不能只委托
add_button事件而不用担心focus? -
好吧,我在initialCollection 的主体中做的不仅仅是附加事件(计算子子项、显示与否、调用其他函数......)。至于这个例子,我对我在新添加的“.collection”上使用的简单示例感到满意。你还有什么想法?
标签: javascript jquery events jquery-events