0
var isAnyBool = $(selector)
 .filter(function(){ return this.style.display !== "none"; })
 .length;

// if (isAnyBool) { .. }

这按预期工作,但当只需要简单的真/假时,不必要地计算所有元素。如何改进以提高效率?

更新:由于visible不知道元素是否直接隐藏,或者某些父母实际上是隐藏的,所以我必须检查style.display或功能相同的东西

4

6 回答 6

6

我不知道性能效率,但这更容易阅读:

var isAnyBool = $(selector).is(':visible');

编辑#2:

我认为@dandavis 的回答是最好的

于 2013-06-27T20:10:02.980 回答
2

您可以使用具有相同回调的.is()方法,而不是过滤和计算元素:

var isAnyBool = $(selector).is(function(){ return this.style.display !== "none"; })
于 2013-06-27T20:17:27.237 回答
2

你可以让它变得简单:visible

var isAnyBool = $(selector).filter(':visible').length;
于 2013-06-27T20:10:21.393 回答
2
var isAnyBool =  $(selector+"[style*='display: none']").length > 0 ;

should be MUCH faster in modern browsers than iteration of any type.

since jQuery's :visible can be affected by more than just style.display, it's not the right tool for this job.

this checks the style attrib only, and does so without js iteration, making it the fastest and simplest solution offered at time of writing.

于 2013-06-27T20:15:13.103 回答
1

不能确定这是否或多或少是开销,但如果你这样做的话,对我来说似乎更清晰:

$(selectSomeStuff).filter(!$(this).is(':visible'));

...或可测试变量

var isAnyBool = $(selectSomeStuff).filter(!$(this).is(':visible')).length

...也许好像声明

if ($(selectSomeStuff).filter(!$(this).is(':visible'))){
  var isAnyBool = true;
  // OR
  //.. do stuff here ...
}
于 2013-06-27T20:12:33.260 回答
1

它不算数..length是属性而不是函数。所以当你打电话时没有太多事情发生.length

我不会存储长度,而是存储结果以防万一它可以在其他地方使用。

var mySelector = $(selector).filter(function(){ return this.style.display !== "none"; })

if (mySelector.length) { .. }
于 2013-06-27T20:08:04.863 回答