2014-03-05 56 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