jquery variable outside function
How can I update a variable outside of a function? For example I have this:
var max_index = 0;
//loop through the z-index's
$(".widget_container").each(function(){
if($(this).attr("z-index") > max_index){
max_index = $(this).attr("z-index") + 1;
}
});
alert(max_index);
The only problem with this is that max_index
is always alerting开发者_JAVA百科 0
. How can I have that update the max_index
?
Yes, you can update the variable, it's accessible from the outer closure, the problem is that z-index
is not an attribute, it is a CSS property, you can get it using the jQuery css function:
var max_index = 0;
//loop through the z-index's
$(".widget_container").each(function(){
if($(this).css('zIndex') > max_index){
max_index = +$(this).css('zIndex') + 1;
}
});
alert(max_index);
Notice that I use a plus sign before the addition, that is the unary plus operator, it converts the zIndex
value to number, since this function returns strings, and if one of the operands of the +
operator is a string, a concatenation is done ( "0" + 1 = "01"
).
Also note that the CSS properties that contain dashes, like background-color
or font-size
, are accessed removing the dash, and capitalizing the next word.
I think
$(this).attr("z-index")
should be
$(this).css("z-index")
This returns a string
Use:
parseInt($(this).css("z-index"))
精彩评论