2012-02-24 71 views
0

我一直在嘗試了幾天到:jQuery的:引用和更新內部功能之外的變量

  1. 設置變量的值「W」
  2. 更新「this.paneWidth = W; 「在構造函數中,每次窗口加載或調整大小。

的問題,我面對:

  1. JQuery的第一次運行該JS構造函數,並返回 「W」 值未定義,我不知道如何解決
  2. 我希望能夠在窗口加載或調整大小時更新構造函數值,但迄今爲止失敗了。

請幫忙!謝謝!

jQuery.event.add(window, "load", resizeFrame); 
jQuery.event.add(window, "resize", resizeFrame); 

var h, 
    w, 
    sliderWidth; 

function resizeFrame() { 
    h = $(window).height(); 
    w = $(window).width(); // assign value to variable 
    sliderWidth = (w * 10); 
    $("div.slider").css('width',sliderWidth); 
    $("div.pane").css('width',w); 
} 

/************ JS CONSTRUCTOR ************/ 
function Slider(container, nav) { 
    this.container = container; 
    this.nav = nav; 
    this.panes = this.container.find('div.pane'); 
    this.paneWidth = w; // referencing variable 
    this.panesLength = this.panes.length; 
    this.current = 0; 
    console.log('pane width = ' + w); 

} 

回答

0

您可以在構造函數中定義全局變量。

function resizeFrame() { 
    h = $(window).height(); 
    w = $(window).width(); // assign value to variable 
    sliderWidth = (w * 10); 
    $("div.slider").css('width',sliderWidth); 
    $("div.pane").css('width',w); 
} 

jQuery.event.add(window, "load", resizeFrame); 
jQuery.event.add(window, "resize", resizeFrame); 

/************ JS CONSTRUCTOR ************/ 
function Slider(container, nav) { 
    h = typeof(h) == 'undefined' ? null : h; 
    w = typeof(w) == 'undefined' ? null : w; 
    sliderWidth = typeof(sliderWidth) == 'undefined' ? null : sliderWidth; 

    this.container = container; 
    this.nav = nav; 
    //this.panes = this.container.find('div.pane'); 
    this.paneWidth = w; // referencing variable 
    //this.panesLength = this.panes.length; 
    this.current = 0; 
    console.log('pane width = ' + w); 

} 
new Slider();