var isAnyBool = $(selector)
.filter(function(){ return this.style.display !== "none"; })
.length;
// if (isAnyBool) { .. }
This works as expected but needlessly counts all elements when all it's needed is simple true/false. How it could be improved to be more efficient?
UPDATE: since visible
doesn't know if element is directly hidden, or some of the parents are actually hidden, I have to check style.display
or something equal in functionality
var isAnyBool = $(selector)
.filter(function(){ return this.style.display !== "none"; })
.length;
// if (isAnyBool) { .. }
This works as expected but needlessly counts all elements when all it's needed is simple true/false. How it could be improved to be more efficient?
UPDATE: since visible
doesn't know if element is directly hidden, or some of the parents are actually hidden, I have to check style.display
or something equal in functionality
-
1
$('*').filter(':hidden').length
? – PlantTheIdea Commented Jun 27, 2013 at 20:09 - @PlantTheIdea check update section – mpapec Commented Jun 27, 2013 at 20:20
- some benchmarks, jsperf./test-display/3 – mpapec Commented Jun 27, 2013 at 21:58
6 Answers
Reset to default 6I don't know about performance efficiency, but this is far easier to read:
var isAnyBool = $(selector).is(':visible');
Edit #2:
I think @dandavis's answer is the best one
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.
You can make it simple with :visible
var isAnyBool = $(selector).filter(':visible').length;
Instead of filtering and counting the elements, you can use the .is()
method with the same callback:
var isAnyBool = $(selector).is(function(){ return this.style.display !== "none"; })
Can't say for sure if this is more or less overhead, but seems more legible to me if you did it something like this:
$(selectSomeStuff).filter(!$(this).is(':visible'));
... or testable variable
var isAnyBool = $(selectSomeStuff).filter(!$(this).is(':visible')).length
... maybe as if statement
if ($(selectSomeStuff).filter(!$(this).is(':visible'))){
var isAnyBool = true;
// OR
//.. do stuff here ...
}
It doesn't count.. length
is a property not a function. So there is not much going on when you call .length
Instead of storing the length, I would store the result in case if it can be used elsewhere.
var mySelector = $(selector).filter(function(){ return this.style.display !== "none"; })
if (mySelector.length) { .. }
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744917546a4600925.html
评论列表(0条)