2012-08-10 101 views
1

真的在這裏簡單的代碼掙扎。我正在檢查#setactionsuccess部分是否存在,如果不是,我想創建它並將其前置到容器中。第一部分工作順利,但它永遠不會去'其他'(和條件滿足 - 我三重檢查)。任何幫助不勝感激。if/else in jquery

if ($('#setactionsuccess')){ 
    var currenttime = new Date(); 
    $('#setactionsuccess').empty(); 
    $('#setactionsuccess').html('<h2>Set successfully deleted</h2><p>Set was successfully removed from this Edition on '+currenttime+'</p>'); 
} else { 
    console.log('here'); 
    var string = '<section class="successful" id="setactionsuccess"><h2>Set successfully deleted</h2><p>Set was successfully removed from this Edition on '+currenttime+'</p></section>'; 
    console.log(string); 
    $('#currentsets').prepend(string); 
} 

回答

1

if ($('#setactionsuccess'))總是返回true
因爲JavaScript檢測開關的nullundefined和jQuery永遠不會返回一個存在的元素nullundefined即使當任何具有ID setactionsuccess劑量的元素存在時
嘗試尋找選擇器的長度$('#setactionsuccess').length

+0

感謝您的詳細解釋。這是有用的知道 – boszlo 2012-08-10 13:12:48

5

試試這個

if($('#setactionsuccess').length > 0) 
+0

非常感謝!輝煌! – boszlo 2012-08-10 12:59:30

1

你從選擇總是得到的東西,即使沒有匹配。您甲肝檢查匹配的數目對0

1

您可以檢查是否使用length

if($('#setactionsuccess').length) { 
    ... 
} 
0

如果你總是有ID #setactionsuccess塊,你需要檢查,如果是空的,這是正確的解決方案:

if ($('#setactionsuccess'.text().length != 0)){ 
    var currenttime = new Date(); 
    $('#setactionsuccess').empty(); 
    $('#setactionsuccess').html('<h2>Set successfully deleted</h2><p>Set was successfully removed from this Edition on '+currenttime+'</p>'); 
} else { 
    console.log('here'); 
    var string = '<section class="successful" id="setactionsuccess"><h2>Set successfully deleted</h2><p>Set was successfully removed from this Edition on '+currenttime+'</p></section>'; 
    console.log(string); 
    $('#currentsets').prepend(string); 
} 
0
if ($(selector).length) 

您可以通過此代碼檢查。