无法从jQuery可排序列表中删除新添加的项目

时间:2013-11-25 23:22:51

标签: javascript jquery jquery-ui

我想从jQuery UI可排序列表中添加然后删除元素/项...

我做错了什么?

我试过了here

<div class="add">Click me to add new item to list</div>
<ul id="sortable">
    <li class="delete">
        <div class="item">these old items can be removed by click on them...</div>
    </li>
    <li class="delete">
        <div class="item">these old items can be removed by click on them...</div>
    </li>
    <li class="delete">
        <div class="item">these old items can be removed by click on them...</div>
    </li>
</ul>

$("#sortable").sortable();

$(".add").click(function () {
    var newItem = '<li class="delete"><div class="item">these <span>new items cannot be removed</span> by click on them...</div></li>';
    $("#sortable").append(newItem);
    $("#sortable").sortable("refresh");

});

$(".delete").click(function () {
    $(this).remove();
});

1 个答案:

答案 0 :(得分:2)

变化

$(".delete").click(function () {
    $(this).remove();
});

$("#sortable").on('click', ".delete", function () {
    $(this).remove();
});

元素是动态插入的,并且在附加事件处理程序时不存在,因此您必须委托在附加处理程序时存在的父元素。