检测jQuery是否删除了元素

时间:2011-11-18 17:15:08

标签: jquery

确定,

所以我有:

<ul>
<li>hello</li>
<li>bye</li>
</ul>

然后:

$('li').click(function(){
$(this).remove();
})

但是我有:

if($('ul li').length == 0){
        $('ul').append('<li>You haven\'t favourited anything. Get to it!</li>');    
    }

但它不起作用!

6 个答案:

答案 0 :(得分:1)

$('li').click(function(){
    $(this).remove();
    if($('ul li').length == 0){
      $('ul').append('<li>You haven\'t favourited anything. Get to it!</li>');    
    }
});

如果你把if语句放在回调之外,它会在页面加载时测试“no li elements”,基本上。您希望它在删除之后测试“无li元素”,因此正确的位置是在删除之后执行此操作。 :)

答案 1 :(得分:0)

这将检查文档加载时的列表项以及用户是否单击所有列表项:

$(document).ready(function() {

checklist();

$('li').click(function(){
 $(this).remove();
 checklist();
})

function checklist() {
    if($('ul li').length == 0) $('ul').append('<li>You haven\'t favourited anything. Get to it!</li>'); } 

 });

http://jsfiddle.net/pcY54/4/

答案 2 :(得分:0)

我认为你想要的只是将if块放在click处理程序中,因此它会在删除元素后重新评估,然后添加该消息。因为它只是在页面加载时运行一次,而且再也不会。

答案 3 :(得分:0)

似乎工作正常,这是一个jsfiddle:http://jsfiddle.net/pcY54/2/

//use jQuery 1.7's `.on()` function to delegate an event handler to the click event
$('ul').on('click', 'li', function(){

    //remove the clicked `<li>` element
    $(this).remove();

    //check to see if there are any `<li>` elements left
    if($('ul li').length == 0){

        //if there are no `<li>` elements then add one with a default message
        $('ul').append('<li>You haven\'t favourited anything. Get to it!</li>');    
    }
});

答案 4 :(得分:0)

点击它们后,您需要检查是否存在任何li:

$('li').click(function(){
    $(this).remove();
    checkLiLength()
})

function checkLiLength(){
    if($('ul li').length == 0){
        $('ul').append('<li>You haven\'t favourited anything. Get to it!</li>');    
    }
}

更新小提琴: http://jsfiddle.net/pcY54/1/

答案 5 :(得分:0)

我查看了我的水晶球,这似乎是一个动态列表,您可以在其中添加元素然后将其删除并再次追加等等?

如果是这样,你不能使用bind,但需要在更高级别的元素中使用事件委托,如下所示:

$('ul').delegate("li", "click", function(){
$(this).remove();

    if($('ul li').length <= 0){
        $('ul').append('<li>You haven\'t favourited anything. Get to it!</li>');    
    }
})

jsfiddle:http://jsfiddle.net/pcY54/3/