jquery:如果ul为空

Jus*_*tin 20 jquery html-lists jquery-ui-dialog

好吧,我有一个jQuery对话框,其中有一个表单,我在我的智慧结束时试图弄清楚...让我看看我是否可以用语言表达我想要做的事情..

我有3个文本框. #apInterest,#apPayment#apPrincipal在正确的顺序.

我想要做的基本英语术语:

#apInterestif .val小于0或大于99.99的密钥上触发错误..否则检查ul#mylist它是否有li,如果没有.hide

#apPaymentif .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();
    }
}
});
Run Code Online (Sandbox Code Playgroud)

虽然我也试过了

if ($("#mylist :not(:contains(li))") ){
$('#popuperrors').hide();
}
Run Code Online (Sandbox Code Playgroud)

对于所有3个文本框我都有类似的功能,但我尝试过的功能似乎都没有...有关如何完成此功能的任何想法

Wul*_*ulf 61

if ($('#mylist li').length == 0) ...
Run Code Online (Sandbox Code Playgroud)

  • 这是Justin的一个常见且容易理解的错误.`$("#mylist:not(:contains(li))")`永远不会为null; 它总会产生一个jQuery对象,即使选择器没有匹配.像这样测试对象的长度是要走的路. (5认同)

Sim*_*lGy 6

我喜欢使用这个children()方法,因为它读得很好,即使你已经缓存了ul的选择器,它也能正常工作.这是它的样子:

$myList = $('#myList')
if ( $myList.children().length === 0 ) ...
Run Code Online (Sandbox Code Playgroud)