jQuery:如果 UL 为空

22

我有一个jQuery对话框,其中包含一个表单,我已经尽尽力地尝试了解它...让我们看看我正在努力做什么...

我有三个文本框。按照确切的顺序是#apInterest#apPayment#apPrincipal

我试图做的基本英语术语:

#apInterest上按键,如果.val小于0或大于99.99,则触发错误...否则检查ul#mylist是否有任何li,如果没有.hide

#apPayment上按键,如果.val小于0,则触发错误,否则检查列表中的li,如果不存在,则隐藏。

#apPrincipal#apPayment完全相同。

我目前拥有的内容:

$('#apInterest').live("keyup", function(e) {
var parent = $('.inter').parents("ul:first");
if ($('#apInterest').val() < 0 || $('#apInterest').val() > 99.99) {
    $('.inter').remove();
    $('#mylist').append('<li class="inter">Interest Rate cannot be below 0 or above 99.99</li>');
    $('#popuperrors').show();
    $(this).addClass('error');
} else {
    $(this).removeClass('error');
    $('.inter').remove();
    alert(parent.children().text);
    if (parent.children().length == 0){
        $('#popuperrors').hide();
    }
}
});

虽然我也尝试过

if ($("#mylist :not(:contains(li))") ){
$('#popuperrors').hide();
}

我有一个类似于这样的函数,用于处理三个文本框,但是我尝试过的所有方法似乎都不起作用...有没有关于如何完成这个的想法


可能是重复的问题:jquery if div id has children - Felix Kling
3个回答

66
if ($('#mylist li').length == 0) ...

5
这是 Justin 常见且易于理解的错误。 $("#mylist :not(:contains(li))") 永远不会是空值,在选择器未匹配任何内容时,它也会生成一个jQuery对象。测试对象的长度是正确的方法。 - Blazemonger
1
最好这样比较:$('#mylist li').length === 0 - Ajey

8

我喜欢使用children()方法,因为它读起来很顺畅,并且即使您已经缓存了ul的选择器,它也可以正常工作。以下是示例:

$myList = $('#myList')
if ( $myList.children().length === 0 ) ...

3

jQuery总是返回一个元素数组。如果没有找到匹配项,则该数组将为空。在Javascript中,空数组的值为true:

console.log( !![] ); // logs: true

你想要检查返回集的长度:
if ( ! $("#mylist li").length ){
   $('#popuperrors').hide();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接