2011-08-30 91 views
17

好吧我有一個jQuery對話框,它有一個表單,我在我的智慧結束試圖弄清楚...讓我看看我是否可以口頭說明我正在嘗試做什麼。 。jquery:如果ul是空的

我有3個文本框。 #apInterest,#apPayment#apPrincipal。什麼我試圖做

基本的英語術語:

#apInterest如果.val比99.99觸發錯誤更大小於0或者KEYUP ..否則檢查ul#mylist如果有任何li,如果不是.hide

on keyup #apPayment if .val is less than 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(); 
} 

我有類似的這種對所有功能3文本框,但沒有我所嘗試似乎工作..任何想法如何完成此

+0

可能重複[jQuery的,如果DIV ID有孩子(http://stackoverflow.com/questions/1526873/jquery-if-div-id-has-children) –

回答

49
if ($('#mylist li').length == 0) ... 
+5

這是賈斯汀方面常見而且容易理解的錯誤。 '$(「#mylist:not(:contains(li))」)'永遠不會爲空;它將始終生成一個jQuery對象,即使選擇器沒有匹配。測試像這樣的對象的長度是要走的路。 – Blazemonger

+0

這對我很有用,所以約瑟夫西爾伯的帖子 – Justin

+0

你最好比較$('#mylist li')。長度=== 0像這樣 – Ajey

3

jQuery總是返回一個元素數組。如果未找到匹配項,則數組將爲空。在Javascript空數組的值爲true:

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

你要檢查返回集的長度:

if (! $("#mylist li").length){ 
    $('#popuperrors').hide(); 
} 
+0

它爲它工作,雖然...我都嘗試了兩個。 – Justin

5

我喜歡用children()方法,因爲它讀取精美,它,如果你的作品甚至已經爲你的ul緩存了選擇器。這裏是什麼樣子:

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