2014-03-05 54 views
0

我想輸入一個if,只要jQuery對象的值是空的而且dom元素不是標籤或跨度。所以,我有如果子句工作不正常

$('.container').children().each(function (index, item2){ 
    if ($(item2).val()=== '' && (item2.tagName.toLowerCase() !== 'label' || item2.tagName.toLowerCase() !== 'span')){ 
     //do stuff here 
     console.log("tag: "+item2.tagName.toLowerCase()); 
    } 
}); 

,但在控制檯中我得到

tag: label 

這意味着它不能正常工作。我在那裏錯過了什麼?

+1

它應該是'$(item2).val()!=='''。 – Andy

+0

更正了它我想輸入如果當值爲空時對所有人抱歉 – Apostolos

回答

0

你的代碼是:

$('.container').children().each(function (index, item2){ 
    if ($(item2).val()=== '' && (item2.tagName.toLowerCase() !== 'label' || item2.tagName.toLowerCase() !== 'span')){   
    console.log("tag: "+item2.tagName.toLowerCase()); 
    } 
}); 

在這裏,你寫你的條件: - $(item2).val() === '' && (item2.tagName.toLowerCase() !== 'label' || item2.tagName.toLowerCase() !== 'span')

首先,如果你想允許非空值元素使用!==而不是使用===所有(如@Rory麥克羅桑建議)。

現在我們談談你的第二個條件,即 - (item2.tagName.toLowerCase() !== 'label' || item2.tagName.toLowerCase() !== 'span')

意味着這裏您允許,如果元素是LABEL OR SPAN

所以,你的病情進入以下四種方式 -

(false || true) ====> true // Element is label 

(true || false) ====> true // Element is span 

(true || true) ====> true // Element is not a span and not a label 

(false || false) ====> false // Element is a span and also an label [this condition never satisfied] 

我想,在這裏你就錯了。您應該使用在以下條件(如果你不允許這兩個類型的元素) -

$(item2).val() === '' && (item2.tagName.toLowerCase() !== 'label' && item2.tagName.toLowerCase() !== 'span')

總之你必須使用&&/AND而不是使用||/OR

1

如果要輸入條件,如果值不爲空您需要使用!==而不是===

if ($(item2).val() !== '' && (item2.tagName.toLowerCase() !== 'label' || item2.tagName.toLowerCase() !== 'span')) { 
    // your code... 
} 
1

我會重寫到

$('.container').children().each(function (index, item2){ 
    if (item2.value) { 

    } 
}); 

SPAN或標籤沒有價值,所以那些失敗的條件反正

+0

@ A.Wolff - 是的,一個空字符串是虛假的,所以檢查長度不應該是必需的。 – adeneo

+0

這是這裏最簡潔的答案,較少upvoted(不包括我)。奇怪的是,有時候...... –

2

你的條件是錯誤,請嘗試以下:

$('.container').children().each(function() { 
    if ($(this).val() !== '' && !$(this).is('span') && !$(this).is('label')) { 
     console.log("tag: "+item2.tagName.toLowerCase()); 
    } 
}); 

但是spanlabel沒有value屬性,如果您的意思是檢查元素是否沒有子元素(包括文本節點),則有:empty選擇器。

$('.container').children().each(function() { 
    if (!$(this).is(':empty, span, label')) { 
     console.log(this); 
    } 
}); 

Check the demo

+0

你也可以將標籤/跨度測試與'!$(this).is('span,label')' –

+0

問題結合起來,第二個問題是輸入,即使有值, –

+0

我喜歡is方法不知道它 – Apostolos