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

时间:2013-11-26 15:53:56

标签: javascript jquery jquery-ui

<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 <span class="delBtn">DEL</span></div>
    </li>
    <li class="delete">
        <div class="item">these old items can be removed by click on <span class="delBtn">DEL</span></div>
    </li>
    <li class="delete">
        <div class="item">these old items can be removed by click on <span class="delBtn">DEL</span></div>
    </li>
</ul>


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

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

$("#sortable").delegate('.delBtn', 'click', function() {
  alert("A click happened, it was captured at #commonParent and this alert ran");      
});

而不是提醒,我想删除列表项... 请帮帮我,我该怎么做?!

你可以try it here ......

3 个答案:

答案 0 :(得分:0)

好吧,如果您使用的是jquery1.6 +,请使用on而不是delegate ..

$("#sortable").on('click','.delBtn', function() {
   alert("A click happened, it was captured at #commonParent and this alert ran"); 
   $(this).parents('.delete').remove();
    //or
   $(this).closest('.delete').remove();
});

remove()将其从DOM中删除。

parents()closest()选择器可选择li元素

fiddle here

答案 1 :(得分:0)

请尝试.on

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

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

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

小提琴:http://jsfiddle.net/MvnEv/111/

答案 2 :(得分:0)

你可以做这样的事情

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

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

$("#sortable").delegate('.delBtn', 'click', function() {
  $(this).closest("div").remove();
});

fiddle