jquery选择器问题:仅在隐藏所有元素时执行某些操作

只有当给定ul中的所有li都被隐藏时,我才需要做一些事情。这似乎没有办法。 有办法吗?

if ($('#some_ul li:hidden')) { // do something only if all 'li's in a given ul are hidden } 

检查返回元素的length属性。

 if ( !$('#some_ul li:visible').length ) { // do something only if all 'li's in a given ul are hidden } 

编辑:将隐藏更改为可见


编辑:澄清使用.length属性进行布尔测试。 请参阅本答复底部的进一步说明。

$('#some_ul li:visible').length返回找到的元素数。 数字值等于true或false。

! 给你的真/假值否定。

因此,如果$('#some_ul li:visible').length找到0个可见元素,这与返回false相同。

当你放置! 在它后面,它的布尔值反转为true 。 因此,如果找不到visible元素,则if()的代码将运行。

它与完成相同:

 if ( $('#some_ul li:visible').length == 0 ) { // do something only if all 'li's in a given ul are hidden } 

…取$('#some_ul li:visible').length数值,并使用==运算符将其转换为布尔值。


要使用:hidden您需要先获取总长度,然后将其与隐藏长度进行比较。

 var total = $('#some_ul li'); if ( $('#some_ul li:hidden').length == total ) { // do something only if all 'li's in a given ul are hidden } 

编辑:为了回应您的评论,为了澄清,有几个值将等同于测试中的真/假。

以下是一些等于false的值的示例:

 var someVariable; // someVariable is undefined, equates to false var someVariable = ''; // someVariable is an empty string, equates to false var someVariable = false; // someVariable is a boolean false, equates to false var someVariable = 0; // someVariable is number zero, equates to false var someVariable = Number('a'); // someVariable is NaN (Not a Number), equates to false var someVariable = null; // someVariable is null, equates to false 

以下是一些等同于true的示例:

 var someVariable = "false"; // someVariable is a string, equates to true var someVariable = 123; // someVariable is a number greater than 0, equates to true var someVariable = -123; // someVariable is a number less than 0, equates to true var someVariable = true; // someVariable is a boolean true, equates to true var someVariable = !false; // someVariable is a negated value that would // otherwise be false, equates to true 

如果您对任何值的有效布尔值感到好奇,请放置!! 在它之前。

 alert( !!123 ); // Alerts true 

第一个! 将值转换为其有效布尔值的反转值。 第二个! 将其转换回有效的布尔值。

例如:

 var a; // an undefined variable alert( a ); // alerts undefined, logically equates to 'false' alert( !a ); // alerts the boolean opposite of undefined, which is 'true' alert( !!a ); // alerts the converts the boolean opposite 'true' back to 'false' 
 $("ul:not(:has(li:visible))") 

这将选择那些没有可见

  • 子项的

      。 检查它的length属性以查看是否有任何属性,或者调用它上面的each()来为它们中的每一个做一些事情。

      你可以这样做:

       if ($('#some_ul li').is(':hidden')) { // do something only if all 'li's in a given ul are hidden } 

      我在想这就是你想要的

       if ( $('#some_ul li:hidden').length == $('#some_ul li').length ) { // do something only if all 'li's in a given ul are hidden }