2009-10-30 79 views
1

如何更新函數外的變量?例如,我有這樣的:jquery變量外函數

 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); 

與此唯一的問題是max_index總是提醒0。我怎麼能更新max_index

回答

3

是的,你可以更新變量,它是從外closure訪問,問題是z-index不是一個屬性,它是一個CSS屬性,你可以使用jQuery css功能得到它:

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); 

請注意,我在加入之前使用加號,也就是一元加運算,將其轉換的zIndex值數目,因爲此函數返回字符串,如果+操作的其中一個操作數是字符串,串聯完成("0" + 1 = "01")。

另請注意,包含破折號的CSS屬性(如background-colorfont-size)可以通過刪除短劃線和大寫下一個單詞來訪問。

+0

感謝對不起我不是想笑。謝謝您的幫助 – ngreenwood6 2009-10-30 03:13:10

0

我覺得

$(this).attr("z-index") 

應該

$(this).css("z-index") 

這會返回一個字符串

用途:

parseInt($(this).css("z-index"))