如果两个元素不存在,则调用函数。 JavaScript的

时间:2014-03-20 13:46:49

标签: javascript

我需要检查是否存在两个元素,如果它们不是,则调用函数。

这不起作用。有人有什么建议吗?

var one = $('.one span');
var two = $('.two span');
(one.length && two.length) ? console.log('') : thisFunc();

5 个答案:

答案 0 :(得分:2)

考虑组合你的选择器。

var both = $('.one span, .two span');

if (!both.length)
    thisFunc();

这更具可读性和更好的性能,因为文档只迭代一次。

答案 1 :(得分:1)

您的jQuery选择器正在返回一个对象。对象有一个长度。长度是一个数字。如果该选择器没有匹配项,则长度为0。就个人而言,我宁愿明确并使用length === 0

(one.length === 0  && two.length === 0) ? thisFunc() : console.log('');

这是自我记录:如果one的长度为0two的长度为0,则运行您的功能。

当然,0在布尔上下文中求值为false,所以你可以这样做:

(!one.length && !two.length) ? thisFunc() : console.log('');

!(one.length || two.length) ? thisFunc() : console.log('');

如果您愿意。

目前,如果两个元素都不存在,则会评估三元运算符的false面,因为:

true && false === false
false && true === false
false && false === false

答案 2 :(得分:1)

我认为你的逻辑倒退了。如果one.length为0且two.length为0,那么您正在寻找要触发的函数。这意味着您需要!(one.length || two.length)。所以你的例子应该是:

var one = $('.one span');
var two = $('.two span');
(one.length || two.length) ? console.log('') : thisFunc();

De Morgan定律(wikipedia link)描述了逻辑not运算符影响连词(&&)和析取(||)的方式。基本上,这说:

"not (A and B)" is the same as "(not A) or (not B)"
"not (A or B)" is the same as "(not A) and (not B)"

答案 3 :(得分:1)

我认为你所追求的答案是

var one = $('.one span');
var two = $('.two span');
(!one.length && !two.length) ? thisFunc() : console.log('')

如果我理解你的要求,那么你的逻辑是有缺陷的,因为如果两者都有长度,你就会登录到控制台,否则你会调用你的函数 - 如果 两者都会发生这种情况没有长度

答案 4 :(得分:0)

放一个!在它面前?

!(one.length && two.length) ? console.log('') : thisFunc();

切换你的三元操作数?

(one.length && two.length) ? thisFunc() : console.log('')

Demorgan的法律?

!one.length || !two.length ? console.log('') : thisFunc();

或者你的意思是改变逻辑?

!(one.length || two.length) ? console.log('') : thisFunc();

总之,我仍然不知道你在谈论什么,并且帽子中的“BOTH”没有澄清。其中一个或几个可能是你想要的,因为我涵盖了你可以做的大部分事情。