如何使用jQuery动态地将点击处理程序添加到li

时间:2013-05-09 21:18:23

标签: jquery

我正在尝试将点击处理程序添加到通过jQuery添加到DOM的li。我认为这就是你做到的方式:

jQuery('.deleteUpload').on('click', '.deleteUpload', function() {
    var strDocId = jQuery(this).prop('id');
    //if (confirm('Are you sure you want to delete this resource') == true) {
        $.post('/study-clubs/meetings/delete-upload', {strDocId : strDocId},
            function(objData){
                console.log(objData);
            }
        );
        jQuery('li#' + strDocId).remove();
    //}

    return false;
});

这是我的标记:

<li class="pdf deleteLi" id="<?php echo $this->escape($this->objDocRow->id); ?>">
   <label><input type="radio" name="documents[1]" value="0" /> Pre-Meeting</label> &nbsp;
   <label><input type="radio" name="documents[1]" value="1" /> Post-Meeting</label> &nbsp;
   <label><input type="radio" name="documents[1]" value="2" checked /> Do Not Use</label> &nbsp;
   <a href="#" class="deleteUpload" id="2">Delete</a> &nbsp;
   <a href="/..."><?php echo substr($this->escape($this->objDocRow->doc_title), 0, -4); ?></a>
</li>

当您点击li标记a时,我想删除deleteUpload。我究竟做错了什么?当我点击它时,我被带到页面顶部。我还在jQuery中尝试了deleteLi而不是deleteUpload,但这也没有用。

2 个答案:

答案 0 :(得分:2)

尝试将第一行更改为:

jQuery('.deleteLi').on('click', '.deleteUpload', function() {

答案 1 :(得分:1)

不需要第二个选择器。有了它,jquery会查找具有deleteUpload类的.deleteUpload子代。

jQuery('.deleteUpload').on('click', function() {
    var strDocId = jQuery(this).prop('id');
    //if (confirm('Are you sure you want to delete this resource') == true) {
        $.post('/study-clubs/meetings/delete-upload', {strDocId : strDocId},
            function(objData){
                console.log(objData);
            }
        );
        jQuery('li#' + strDocId).remove();
    //}

    return false;
});