jquery:如果 ul 为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7247272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery: if ul is empty
提问by Justin
Okay I have a jQuery dialog box which has a form in it and I am at my wits end trying to figure this out... Lets see if I can verbalize what I am trying to do..
好的,我有一个 jQuery 对话框,里面有一个表单,我在我的智慧尽头试图解决这个问题......让我看看我是否可以用语言表达我正在尝试做的事情......
I have 3 text boxes. #apInterest
, #apPayment
and #apPrincipal
in that exact order.
我有 3 个文本框。 #apInterest
,#apPayment
并#apPrincipal
按照这个确切的顺序。
basic english terms of what i am trying to do:
我正在尝试做的基本英语术语:
on keyup in #apInterest
if .val
is less than 0 or greater than 99.99 trigger an error.. else check ul#mylist
if it has any li
, if not .hide
在 keyup 中#apInterest
if.val
小于 0 或大于 99.99 触发错误.. else 检查ul#mylist
它是否有任何li
,如果没有.hide
on keyup in #apPayment
if .val
is less than 0 trigger an error else check the list for li
hide if not.
#apPayment
如果.val
小于 0 ,则在 keyup 上触发错误,否则检查列表是否li
隐藏。
#apPrincipal
is the same thing exactly as #apPayment
#apPrincipal
完全一样 #apPayment
what I have right this moment
此刻我有什么权利
$('#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();
}
}
});
Although I have also tried
虽然我也尝试过
if ($("#mylist :not(:contains(li))") ){
$('#popuperrors').hide();
}
I had a function similar to this for all 3 textboxes but none of what I have tried seems to work.. any ideas on how to complete this
我对所有 3 个文本框都有一个与此类似的功能,但我尝试过的所有功能似乎都不起作用..有关如何完成此操作的任何想法
回答by Wulf
if ($('#mylist li').length == 0) ...
回答by SimplGy
I like using the children()
method because it reads nicely and it works even if you've already cached the selector for your ul. Here's what it looks like:
我喜欢使用这个children()
方法,因为它读起来很好,即使你已经为你的 ul 缓存了选择器,它也能工作。这是它的样子:
$myList = $('#myList')
if ( $myList.children().length === 0 ) ...
回答by Joseph Silber
jQuery always returns an array of elements. If no matches were found, the array will be empty. An empty array in Javascript evaluates to true:
jQuery 总是返回一个元素数组。如果未找到匹配项,则数组将为空。Javascript 中的空数组计算结果为 true:
console.log( !![] ); // logs: true
You want to check the length of the returned set:
您要检查返回集的长度:
if ( ! $("#mylist li").length ){
$('#popuperrors').hide();
}