jquery:引用和更新函数内部的外部变量

时间:2012-02-24 23:13:10

标签: jquery variables constructor

我已经尝试了好几天:

  1. 设置变量“w”的值
  2. 更新“this.paneWidth = w;”每次窗口加载或调整大小时,在构造函数中。
  3. 我遇到的问题:

    1. JQuery首先运行JS Constructor,并将“w”值返回为 undefined ,我不知道如何修复
    2. 我希望每次窗口加载或调整大小时都能更新构造函数值,但到目前为止都失败了。
    3. 请帮忙!谢谢!

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

1 个答案:

答案 0 :(得分: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();