简体   繁体   English

jQuery对附加项目的单击操作

[英]jQuery click action on appended item

Having looked at the documentation I know that the issue lies with the fact the item I want to delete is being appended. 看了文档后,我知道问题出在我要删除的项目被附加的事实上。 Though from I can see using .on should allow for this. 虽然从我可以看到使用.on应该允许这样做。 I am appending some content to a list with a button I want to delete the appended content when clicked. 我将一些内容添加到带有按钮的列表中,我想在单击时删除添加的内容。

<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();
    });

The content appends fine, but the click function for remaking it will not fire. 内容可以很好地添加,但是重新生成它的单击功能将不会触发。 It does work however if the content is already on the page, eg no appended later. 但是,如果内容已经在页面上(例如,以后没有追加),它确实可以工作。

As soon as child-delete is appended to the DOM, $('.child-delete').on('click', ..) will not work beacause jQuery can not find it. 一旦将child-delete添加到DOM, $('.child-delete').on('click', ..)将无法正常工作,因为jQuery无法找到它。

Instead use event delegation : 而是使用事件委托

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM