Can JQuery each function be used on DOM objects that are hidden?
I am trying to find the total outer width of all "li" elements in a menu but my code don't seem to work so I am wondering is it because the parent UL element is set to display none?
If so how to get around this?
<ul>
<li>menu item 1</li>
<li>menu item 2<ul>
<li>sub menu item 1</li>
<li>sub menu item 2</li>
</ul></li>
</ul>
So obviously my sub menu item is set to display none un开发者_JS百科til it is hovered over.
And my JS is like this
var totalWidth = 0;
jQuery("ul ul li").each(function() {
totalWidth += jQuery(this).outerWidth();
});
alert(totalWidth);
When I alert this, it is always zero...
Anyway you can hack your way out of it...:
var totalWidth = 0;
jQuery("ul ul").show();
jQuery("ul ul li").each(function() {
totalWidth += jQuery(this).outerWidth();
});
jQuery("ul ul").hide();
alert(totalWidth);
Not sure you have hidden the ul ul
selector but see the system?
Some CSS hacks maybe:
http://jsfiddle.net/ywtBH/
http://jsfiddle.net/ywtBH/2/
http://jsfiddle.net/ywtBH/5/
After chat:
The solution was to put white-space:none;
and... See: http://jsfiddle.net/dGhAp/2/
With float:left;
--- PARENT ---------------------
|------------------------ |
| elem1 | elem2 | |
| | | |
| | | |
-------------------------
elem3 |
|
|
-------------
With display:inline-block;
--- PARENT ---------------------
|-------------------------------|---
| elem1 | elem2 |elem3 | |
| | | | |
| | | | |
------------------------------------
The issue isn't the enumeration but the fact that outerWidth returns zero for all of the enumerated elements because they are not displayed.
If you can change the way you hide your UL element to use visibility: hidden
instead of display: none
then outerWidth should return an actual width, which would solve your problem.
What is this function for? You coudl position the menu items off the screen using something like top: 999999px so the user doesn't see it but its hidden. By doing that jquery can pick out the width. Part of your hover event would be to set/remove the top style so that its positioned as expected.
精彩评论