【问题标题】:jQuery click action on appended item附加项目上的jQuery单击操作
【发布时间】:2014-12-31 19:21:02
【问题描述】:

查看文档后,我知道问题在于我要删除的项目正在被附加。虽然从我可以看到使用 .on 应该允许这样做。我正在使用一个按钮将一些内容附加到列表中,我想在单击时删除附加的内容。

<ul id="children">
    <li id="child1">
        <label class="narrow-full">Child</label>
        <?php echo form_dropdown('year[]', $years, date('Y')); ?>
    </li>
</ul>

var c = 1;
    $( ".child-add" ).click(function() {
        $( "#child1" ).clone().append( "<span class='child-delete ui-icon ui-icon-trash inline-block'></span>" ).attr('id', 'child'+(++c) ).appendTo( "#children" );
    });

    $( ".child-delete" ).on('click',function() {
        $(this).parent().remove();
    });

内容附加正常,但重制的点击功能不会触发。但是,如果内容已经在页面上,它确实有效,例如以后不加了。

【问题讨论】:

    标签: javascript jquery append


    【解决方案1】:

    只要将child-delete 附加到DOM,$('.child-delete').on('click', ..) 将无法工作,因为jQuery 找不到它。

    改为使用event delegation:

    $(document).on('click', '.child-delete', function() {
        $(this).parent().remove();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-11
      • 1970-01-01
      • 2016-04-28
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多