【问题标题】:How to attach a function which is attaching another function to a yet non existent element?如何附加一个将另一个函数附加到一个尚不存在的元素的函数?
【发布时间】: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


【解决方案1】:

您有几个问题要回答,但我认为您的问题可以通过有效地使用 on() 函数中的第二个参数来解决。

您应该将单击事件附加到将包含具有.collection 类的元素的容器元素。

因此,与其选择具有.collection 类的所有元素并将点击事件绑定到.add_button 元素,不如将其绑定一次到所有.collection 元素的父元素并按@987654326 过滤@像这样:

$('.collection:eq(0)').parent().on('click', '.add_button:eq(0)', function(e) {
  // Logic for when button is clicked.
});

当添加.collection 元素之一时,您不必担心调用某个函数来绑定所有事件。

当然,您可以将 $('.collection').parent() 替换为仅针对该容器的选择器,而无需调用 parent()

【讨论】:

  • 好吧,根据我的评论,我对单击 add_button 不感兴趣,但事实上添加了一个新集合。我所做的不仅仅是聆听点击 add_button 的声音。
  • 通过查看您的代码,您的所有逻辑都在您的.add_button 元素的点击事件中。您可能需要在此处发布更多代码,这样我们才能在此处看到您想要实现的目标。
  • 我刚刚添加了整个代码:确实,在这个 add_button 元素之外还有很多逻辑。感谢您的宝贵时间
猜你喜欢
  • 1970-01-01
  • 2013-02-17
  • 1970-01-01
  • 2014-10-11
  • 1970-01-01
  • 2012-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多